今天覆習下稀疏數組相關思想。java
如上圖所示二維數組,大多值是默認值(0),因此記錄大量無心義的數據意義不大,此時能夠引入稀疏數組。數組
稀疏數組介紹:當一個數組大部分元素爲固定值時,可使用稀疏數組來保存相似數組;spa
public class SparseArray { public static void main(String[] args) { // 建立原始二維數組(0 表示無子,1 表示黑子 2 表示 白子) int chessArr1[][] = new int[11][11]; chessArr1[1][2] = 1; chessArr1[3][3] = 2; chessArr1[5][1] = 2; // 使用 for 循環遍原始二維數組 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++; } } } System.out.println("sum = " + sum); // 建立稀疏數組 int sparseArr[][] = new int[sum + 1][3]; // 爲稀疏數組賦值 sparseArr[0][0] = chessArr1.length; sparseArr[0][1] = chessArr1.length; sparseArr[0][2] = sum; // 便利原始二維數組,進行存放 int n = 0; for (int i = 0; i < chessArr1.length; i++) { for (int j = 0; j < chessArr1.length; j++) { if (chessArr1[i][j] != 0) { n++; sparseArr[n][0] = i; sparseArr[n][1] = j; sparseArr[n][2] = chessArr1[i][j]; } } } // 遍歷稀疏數組 System.out.println("-------------------------------------------稀疏數組---------------------------------"); for (int i = 0; i < sparseArr.length; i++) { System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]); } // 將稀疏數組還原爲原始二維數組 int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]]; for (int i = 1; i < sparseArr.length; i++) { chessArr2[chessArr2[i][0]][chessArr2[i][1]] = chessArr2[i][2]; } System.out.println("-------------------------------------------恢復後的二維數組---------------------------------"); for (int row[] : chessArr1) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } } }
輸出結果以下:code
-------------------------------------------原始二維數組------------------------------- 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 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 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sum = 3 -------------------------------------------稀疏數組--------------------------------- 11 11 3 1 2 1 3 3 2 5 1 2 -------------------------------------------恢復後的二維數組--------------------------- 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 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 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0