01.稀疏矩阵与二维数组相互转化


public class SparseArray {
    //输出二维数组
    public static void consoleArr(int[][] arr){
        for (int[] ints : arr) {
            for (int anInt : ints) {
                System.out.printf("%d	",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
    }
}
原文地址:https://www.cnblogs.com/fly-book/p/11629610.html