稀疏数组和队列

2020-11-12  本文已影响0人  Cook1fan
image.png
image.png
public class SparseArray {

    public static void main(String[] args) {
        // 二维数组 11 * 11
        // 0 = 无, 1 = 黑子,2 = 篮子
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[4][5] = 2;
        // 输出
        for (int[] row : chessArr1) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        // 二维转稀疏
        int sum = 0;
        for (int[] row : chessArr1) {
            for (int data : row) {
                if (data != 0) {
                    sum++;
                }
            }
        }
        System.out.println("sum = " + sum);
        // 创建稀疏
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 0; // 用于记录是第几个非零数据
        for (int row = 0; row < chessArr1.length; row++) {
            for (int col = 0; col < chessArr1[row].length; col++) {
                if (chessArr1[row][col] != 0) {
                    count++;
                    sparseArr[count][0] = row;
                    sparseArr[count][1] = col;
                    sparseArr[count][2] = chessArr1[row][col];
                }
            }
        }
        // 输出稀疏
        System.out.println();
        System.out.println("得到稀疏数组");
        for (int[] row : sparseArr) {
            System.out.printf("%d\t%d\t%d\t", row[0], row[1], row[2]);
            System.out.println();
        }
        System.out.println();

        // 稀疏 转 二维
        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];

        for (int row = 1; row < sparseArr.length; row++) {
            chessArr2[sparseArr[row][0]][sparseArr[row][1]] = sparseArr[row][2];
        }

        for (int[] row : chessArr2) {
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读