1. scenario
331 procedures write, save and exit and have continued on disk function
[Analysis] because a lot of the value of the two-dimensional array is the default value 0, and therefore makes no sense to record a lot of data → sparse array
2. Basic Introduction
- When most of the elements in an array is 0, or a value of the same array, the sparse array can be used to hold the array
- Sparse array processing method
- An array of records, a total of several odd row, how many different values
- And the ranks of the value of records with different values of the elements in an array of small-scale, thereby reducing the size of the program
3. Analysis of ideas
→ sparse array of two-dimensional array
- Traversing the original two-dimensional array, the number of valid data obtained sum
- The sum can create a sparse array {sparseArr} - int [sum + 1] [3]
- The two-dimensional array of valid data stored in the sparseArr
→ sparse array of two-dimensional arrays
- SparseArr first read the first line L1 according to the data to create original two-dimensional array {arr} - int [sparseArr [0] [0]] [sparseArr [0] [1]]
- After a few lines of the re-read data sparse array, and in accordance with the respective position (c1, c2) assigned to the c3 of arr
4. The code implementation
// 创建一个原始的二维数组 11 * 11
// 0 表示没有棋子; 1 表示黑子; 2 表示白子
public class SparseArrayDemo {
public static void printArr(int[][] arr) {
for(int[] row : arr) {
for(int data : row)
System.out.printf("%d\t", data);
System.out.println();
}
}
public static void main(String[] args) {
// 0. 创建棋盘, 摆好棋子
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
System.out.println("棋盘:");
printArr(chessArr1);
// 1. [存盘]二维数组 → 稀疏数组
// 1.1 遍历二维数组, 得到 !0 数据的个数
int sum = 0;
int row = chessArr1.length, column = chessArr1[0].length;
for(int i = 0; i < row; i++)
for(int j = 0; j < column; j++)
if(chessArr1[i][j] != 0)
sum++;
System.out.println("sum = " + sum);
// 1.2 创建对应的稀疏数组
int sparseArr[][] = new int[sum+1][3];
// 给稀疏数组赋值
// L-1
sparseArr[0][0] = row;
sparseArr[0][1] = column;
sparseArr[0][2] = sum;
// L-2 ~ L-sum
// 遍历二维数组, 将 !0 值放入稀疏数组中
int line = 1;
for(int i = 0; i < row; i++)
for(int j = 0; j < column; j++)
if(chessArr1[i][j] != 0) {
sparseArr[line][0] = i;
sparseArr[line][1] = j;
sparseArr[line][2] = chessArr1[i][j];
line++;
}
System.out.println("存盘:");
printArr(sparseArr);
// 2. [复盘]稀疏数组 → 二维数组
// 2.1 读取sparseArr的第一行, 创建棋盘
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
// 2.2 读取 L-2 ~ L-sum, 恢复棋盘
for(int i = 1; i <= sparseArr[0][2]; i++)
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
System.out.println("复盘:");
printArr(chessArr2);
}
}