01.稀疏矩陣與二維數組相互轉化

public class SparseArray {
    //輸出二維數組
    public static void consoleArr(int[][] arr){
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
            System.out.println();
        }
        System.out.println();
    }

    //二維數組轉化爲稀疏矩陣
    public static int[][] arr2ToSparse(int[][] arr){
        int count = 0;
        for (int[] ints : arr) {
            for (int anInt : ints) {
                if (anInt!=0)
                    count++;
            }
        }
        int sparseArr[][] = new int[count+1][3];
        int row = arr.length;
        int col = arr[0].length;
        sparseArr[0][0] = row;
        sparseArr[0][1] = col;
        sparseArr[0][2] = count;
        int l = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (arr[i][j]!=0){
                    l++;
                    sparseArr[l][0] = i;
                    sparseArr[l][1] = j;
                    sparseArr[l][2] = arr[i][j];
                }
            }
        }
        return sparseArr;
    }
    //稀疏矩陣轉化爲二維數組
    public static int[][] sparseToArr2(int[][] arr){
        int row = arr[0][0];
        int col = arr[0][1];
        int count = arr[0][2];
        int[][] chessArr = new int[row][col];
        for (int i = 1; i <= count; i++) {
            chessArr[arr[i][0]][arr[i][1]] = arr[i][2];
        }
        return chessArr;
    }
    public static void main(String[] args){
        // 11*11的棋盤
        // 0表示沒有棋子,1表示黑子,2表示白子
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][4] = 2;
        consoleArr(chessArr);
        //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	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
        System.out.println("二維數組轉化爲稀疏矩陣");
        int[][] sparseArr = arr2ToSparse(chessArr);
        consoleArr(sparseArr);
        //1	2	1
        //2	4	2
        System.out.println("稀疏矩陣轉化爲二維數組");
        consoleArr(sparseToArr2(sparseArr));
        //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	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
    }
}
相關文章
相關標籤/搜索