|
package com.yc.sparseArray; |
|
|
|
import java.io.*; |
|
|
|
public class SparseArray { |
|
public static void main(String[] args) throws IOException { |
|
|
|
|
|
int chessArr1[][] = new int[11][11]; |
|
chessArr1[1][2] = 1; |
|
chessArr1[2][3] = 2; |
|
chessArr1[4][5] = 2; |
|
|
|
System.out.println("原始的二维数组:"); |
|
for (int[] row:chessArr1){ |
|
for(int data:row){ |
|
System.out.printf("%d\t",data); |
|
} |
|
System.out.println(); |
|
} |
|
|
|
|
|
|
|
int sum = 0; |
|
for (int i = 0; i < chessArr1.length; i++) { |
|
for (int j = 0; j < chessArr1.length; j++) { |
|
if(chessArr1[i][j] != 0){ |
|
sum++; |
|
} |
|
} |
|
} |
|
|
|
|
|
int sparseArr[][] = new int[sum+1][3]; |
|
|
|
sparseArr[0][0] = chessArr1.length; |
|
sparseArr[0][1] = chessArr1.length; |
|
sparseArr[0][2] = sum; |
|
|
|
|
|
int count = 0; |
|
for (int i = 0; i < chessArr1.length; i++) { |
|
for (int j = 0; j < chessArr1.length; j++) { |
|
if(chessArr1[i][j] != 0){ |
|
count ++; |
|
sparseArr[count][0] = i; |
|
sparseArr[count][1] = j; |
|
sparseArr[count][2] = chessArr1[i][j]; |
|
} |
|
} |
|
} |
|
|
|
|
|
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d:\\map.data",false)); |
|
BufferedWriter bw = new BufferedWriter(osw); |
|
for (int[] ints : sparseArr) { |
|
bw.write(ints[0]+ " " +ints[1]+ " " +ints[2]); |
|
bw.newLine(); |
|
} |
|
|
|
bw.flush(); |
|
bw.close(); |
|
|
|
|
|
System.out.println(); |
|
System.out.println("得到的稀疏数组为:"); |
|
InputStreamReader isr = new InputStreamReader(new FileInputStream("d:\\map.data")); |
|
BufferedReader br = new BufferedReader(isr); |
|
|
|
for (int i = 0; i < sparseArr.length; i++) { |
|
System.out.println(sparseArr[i][0] + "\t" + |
|
sparseArr[i][1] + "\t" + sparseArr[i][2]); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
String first = br.readLine(); |
|
String[] firstLine = first.split(" "); |
|
int chessArr2[][] = new int[Integer.parseInt(firstLine[0])][Integer.parseInt(firstLine[1])]; |
|
|
|
|
|
String next = null; |
|
while((next=br.readLine()) != null){ |
|
String[] nextLine = next.split(" "); |
|
chessArr2[Integer.parseInt(nextLine[0])][Integer.parseInt(nextLine[1])] = Integer.parseInt(nextLine[2]); |
|
} |
|
|
|
isr.close(); |
|
br.close(); |
|
|
|
System.out.println(); |
|
System.out.println("还原的二维数组:"); |
|
|
|
for (int[] row:chessArr2){ |
|
for(int data:row){ |
|
System.out.printf("%d\t",data); |
|
} |
|
System.out.println(); |
|
} |
|
} |
|
} |