20_稀疏陣列

神莹發表於2024-07-01

06_稀疏陣列

  1. 當一個陣列中大部分元素為0或為同一值時,可以使用稀疏陣列儲存該陣列。
//建立一個11*11的二維陣列,0沒有棋子,1黑棋,2白棋
int[][] array = new int[11][11];
array[1][2] = 1;
array[2][3] = 2;
System.out.println("原始陣列array為:");
for (int[] ints : array) {
    for (int anInt : ints) {
        System.out.print(anInt + "\t");
    }
    System.out.println();
}

int sum = 0;
for (int i = 0; i < 11; i++) {
    for (int j = 0; j < 11; j++) {
        if(array[i][j] != 0){
            sum++;
        }
    }
}
System.out.println("有效值個數:" + sum);

//建立一個稀疏陣列
int[][] array2 = new int[sum+1][3];
//11行11列,有效數為sum個
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
int a = 1;
for (int i = 0; i < 11; i++) {
    for (int j = 0; j < 11; j++) {
        if(array[i][j] != 0){
            array2[a][0] = i;
            array2[a][1] = j;
            array2[a][2] = array[i][j];
            a++;
        }
    }
}
System.out.println("稀疏矩陣array2為:");
for (int[] ints : array2) {
    for (int anInt : ints) {
        System.out.print(anInt + "\t");
    }
    System.out.println();
}

int[][] array3 = new int[array2[0][0]][array2[0][1]];
int b = 1;
for (int i = 0; i < array2[0][0]; i++) {
    for (int j = 0; j < array2[0][1]; j++) {
        if(i == array2[b][0] && j == array2[b][1]){
            array3[i][j] = array2[b][2];
            if(b < array2[0].length - 1){
                b++;
            }
        }else{
            array3[i][j] = 0;
        }
    }
}
System.out.println("解壓後的陣列array3為:");
for (int[] ints : array3) {
    for (int anInt : ints) {
        System.out.print(anInt + "\t");
    }
    System.out.println();
}
原始陣列array為:
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
稀疏矩陣array2為:
11	11	2	
1	2	1	
2	3	2	
解壓後的陣列array3為:
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

小提示

  1. IDEA中可透過敲出array.for快速打出增強for迴圈

相關文章