五子棋:
0 0 0 0
1 0 0 0
0 2 1 0
1:黑子
2:黑子
0:空白 佔大部分,可利用稀疏數組壓縮
稀疏數組的處理方法:
1)記錄數組一共有幾行幾列,有多少個不同的值
2)把具有不同元素的行列記錄在一個小規模的數組 中,從而縮小程序的規模(稀疏數組)。
0 0 2 0 1
0 3 0 6 0
0 0 0 0 4
9 0 0 0 0
a[0]保存行數和列數和非零個數
a[0] |
4 |
5 |
6 |
a[1] |
0 |
2 |
2 |
a[2] |
0 |
4 |
1 |
a[3] |
1 |
1 |
3 |
a[4] |
1 |
3 |
6 |
a[5] |
2 |
4 |
4 |
a[6] |
3 |
0 |
9 |
7個三元數組,7*3=21
2*20=40
代碼:
package Arayy;
public class SparseArray {
public static void main(String[] args) {
//初始化稀疏數組
int chessArr[][] = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][4] = 2;
for(int i=0; i< chessArr.length; i++){
for(int j=0; j<chessArr[i].length; j++){
System.out.print(chessArr[i][j]+"\t");
}
System.out.println();
}
//轉換爲稀疏數組1)統計非零個數:
int sum = 0;
for (int i=0; i<11; i++){
for(int j=0; j<11; j++){
if(chessArr[i][j] != 0){
sum++;
}
}
}
//創建稀疏數組
int sparseArray[][] = new int[sum+1][3];
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum; //chessArr[0]
//遍歷二維數組,將非零的值存入數組sparseArr
int count = 1; //記錄這是第幾個非零值
for (int i=0; i<11; i++){
for(int j=0; j<11; j++){
if(chessArr[i][j] != 0){
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArr[i][j];
count++;
}
}
}
//輸出稀疏數組
for (int i=0; i<sparseArray.length; i++){
System.out.print(sparseArray[i][0]+"\t" + sparseArray[i][1]+"\t" +
sparseArray[i][2]);
System.out.println();
}
//將稀疏數組恢復成二維數組:
//1)先根據第一行創建二維原始數組
//2)後面幾行恢復數值
int chessArr2[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i=1; i<sparseArray.length; i++){
chessArr2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
for (int i=0; i<chessArr2.length; i++){
for(int j=0; j<chessArr2[i].length; j++){
System.out.print(chessArr2[i][j]+" ");
}
System.out.println();
}
}
}
數組存到文件中
課後習題:1)在前面的基礎上,將稀疏數組保存到磁盤上,比如map.data。(2)恢復原來的數組時,讀取map.data進行恢復