Java寫稀疏陣列
阿新 • • 發佈:2021-07-05
稀疏陣列
- 當一個數組中大部分元素為0,或者為同一值的陣列時,可以使用稀疏陣列來儲存該陣列。
- 稀疏陣列的處理方式是:
- 記錄陣列一共有幾行幾列,有多少不同值
- 把具體有不同值的元素和行列及值記錄在一個小規模的陣列中,從而縮小程式的規模
package com.cnblogs; public class Demo { public static void main(String[] args) { //建立一個二維陣列11*11 0:沒有旗子 1:黑子 2:白子 int[][] arr = new int[11][11]; arr[1][2] = 1; arr[2][3] = 2; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j]+ "\t"); } System.out.println(); } System.out.println("==========================================="); //轉換為稀疏陣列儲存 //1.獲取有效值的個數 int sum = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < 11; j++) { if(arr[i][j]!=0){ sum++; } } } System.out.println("輸出有效值的個數為:"+sum); //2.建立一個稀疏陣列的陣列 int[][] arrs = new int[sum+1][3]; arrs[0][0] =11; arrs[0][1] =11; arrs[0][2] =sum; //3.遍歷二維陣列,將非零的值,存放稀疏陣列中 int count = 0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[1].length; j++) { if(arr[i][j]!=0){ count++; arrs[count][0] = i; arrs[count][1] = j; arrs[count][2] = arr[i][j]; } } } //輸出稀疏陣列 for (int i = 0; i < arrs.length; i++) { for (int j = 0; j < arrs[i].length; j++) { System.out.print(arrs[i][j]+ "\t"); } System.out.println(); } System.out.println("==========================================="); System.out.println("還原稀疏陣列:"); //1.讀取稀疏陣列 int[][] array = new int[arrs[0][0]][arrs[0][1]]; //2.給其中的元素還原他的值 for (int i = 1; i < arrs.length; i++) { array[arrs[i][0]][arrs[i][1]] = arrs[i][2]; } //列印還原陣列 for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]+ "\t"); } System.out.println(); } } }
所有列印結果如下: 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 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 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 =========================================== 輸出有效值的個數為:2 11 11 2 1 2 1 2 3 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 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 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