为什么要用稀疏数组比如说以下这种情况
0 0 0 0 0 0 0 4 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 7 0 0
只有两位有效数字其他全是0,很多0值无疑是很浪费空间的,这时我们就会使用稀疏数组来存入他的有效信息
将以上数组转为稀疏数组为:
row column value
4 9 2
0 7 4
3 6 7
第一行 4 9 2 代表的是 4行 7列 2个有效数字
第二行为 第一个有效数字在原数组的第零行 第七列 有效值为4
第三行为 第二个有效数字在原数组的第三行 第六列 有效值为7
小例子:
/**
* 稀疏数组
* @author 20898
*
*/
public class SparseArray {
public static void main(String[] args) {
//定义一个棋盘,和三个初始旗子
int[][] arr = new int[11][11]; //方便写死 行列都为11
arr[0][2] = 1;
arr[2][3] = 2;
arr[6][6] = 10;
int sum = 0;
for(int [] row:arr) {
for(int data:row) {
System.out.print(data+"\t");
if(data!=0) {
sum++;
}
}
System.out.println();
}
System.out.println("sum:"+sum);
SparseArray s = new SparseArray();
//转为稀疏数组
s.printArr(s.arrChangeSpareArr(arr, sum));
//将稀疏数组存入文件
s.save(s.arrChangeSpareArr(arr, sum));
//將稀疏数组从文件读取出来
s.get("pic.txt");
//将稀疏数组转为数组
s.spareArrChangeArr(s.arrChangeSpareArr(arr, sum));
}
//保存到文件中
public void save(int [][] arr) {
try {
FileOutputStream file = new FileOutputStream("pic.txt");
for(int [] row:arr) {
for(int data:row) {
file.write(data);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
//从文件中读取
public void get(String name) {
System.out.println("读取结果:");
int len=0;
try {
FileInputStream fileInputStream = new FileInputStream(name);
byte[] buffer = new byte[1024];
int i=0;
while ((len = fileInputStream.read()) != -1) {//读不到内容返回-1
System.out.print((int)len+"\t");
i++;
if(i%3==0) {
System.out.println();
}
}
} catch ( IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//将数组转为稀疏数组
public int[][] arrChangeSpareArr(int [][]arr ,int sum) {
int[][] spareArray = new int[sum+1][3];
spareArray[0][0] = 11;
spareArray[0][1] = 11;
spareArray[0][2] = sum;
int count = 0;
for(int i=0;i<11;i++) {
for(int j=0;j<11;j++) {
if(arr[i][j]!=0) {
count++;
spareArray[count][0] = i;
spareArray[count][1] = j;
spareArray[count][2] = arr[i][j];
}
}
}
return spareArray;
}
//将稀疏数组转为数组
public void spareArrChangeArr(int[][]spareArray) {
int newrow= spareArray[0][0];
int newcolumn = spareArray[0][1];
int oldRow = spareArray.length;
int oldColumn =spareArray[0].length;
int[][] newArray = new int[newrow][newcolumn];
int x=0,y=0,value=0;
System.out.println("------------"+oldRow+"--"+oldColumn);
for(int i=1;i<oldRow;i++) {
x=spareArray[i][0];
y=spareArray[i][1];
value=spareArray[i][2];
newArray[x][y]=value;
System.out.println("x:"+x+"y:"+y+"value:"+value);
}
printArr(newArray);
}
public void printArr(int [][]arr) {
System.out.println("数组打印:");
for(int [] row:arr) {
for(int data:row) {
System.out.print(data+"\t");
}
System.out.println();
}
}
}