package com.an;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class SparseArray {
public static void main(String[] args) throws Exception {
//创建一个11*11的二维数组
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();
}
//将二维数组转为稀疏数组
//先遍历二维数组,得到非0的个数
int sum=0;
for(int i=0;i<11;i++){
for(int j=0;j<11;j++){
if(chessArr1[i][j]!=0){
sum++;
}
}
}
//创建对应的稀疏数组
int spqreseArr[][]=new int[sum+1][3];
spqreseArr[0][0]=11;
spqreseArr[0][1]=11;
spqreseArr[0][2]=sum;
int count=0;
for(int i=0;i<11;i++){
for(int j=0;j<11;j++){
if(chessArr1[i][j]!=0){
count++;
spqreseArr[count][0]=i;
spqreseArr[count][1]=j;
spqreseArr[count][2]=chessArr1[i][j];
}
}
}
File file = new File("d:\\map.data");
try {
FileWriter out = new FileWriter(file);
for(int i=0;i<spqreseArr.length;i++){
out.write(spqreseArr[i][0]+"\t"+spqreseArr[i][1]+"\t"+spqreseArr[i][2]+"\t");
out.write("\r\n");
}
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("读取文件后的数组");
FileReader fileReader=new FileReader("d:\\map.data");
BufferedReader in=new BufferedReader(fileReader);
System.out.println("读取");
int row=0;
String line=null;
int[][] arr = null;
while((line = in.readLine())!= null){
String[] temp = line.split("\t");
if(row==0){
arr=new int[Integer.parseInt(temp[0])][Integer.parseInt(temp[1])];
row++;
}else{
arr[Integer.valueOf(temp[0])][Integer.valueOf(temp[1])]=Integer.valueOf(temp[2]);
}
}
in.close();
System.out.println("读取的数组");
for(int[] rows:arr){
for(int data:rows){
System.out.printf("%d\t",data);
}
System.out.println();
}
//输出稀疏矩阵
for(int i=0;i<spqreseArr.length;i++){
System.out.printf("%d\t%d\t%d\t\n",spqreseArr[i][0],spqreseArr[i][1],spqreseArr[i][2]);
}
System.out.println();
int chessArr2[][]=new int[spqreseArr[0][0]][spqreseArr[0][1]];
for(int i=1;i<spqreseArr.length;i++){
chessArr2[spqreseArr[i][0]][spqreseArr[i][1]]=spqreseArr[i][2];
}
System.out.println();
System.out.println("恢复后的数组");
for(int[] rows:chessArr2){
for(int data:rows){
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}