代码-稀疏数组

伍陆柒 123 2022-03-27

稀疏数组

数组实现

package cn.ethreal.sparsearry;

public class SparseArray {
    public static void main(String[] args) {
        //1表示黑色,2表示白色
        int[][] origin = new int[11][11];
        origin[1][2] = 1;
        origin[2][3] = 2;
        origin[3][4] = 1;
        //输出原始数组
        System.out.println("这是原数组");
        for (int[] row : origin) {
            for (int col : row) {
                System.out.printf("%d\t", col);
            }
            System.out.println();
        }
        //开始转换稀疏数组
        int sum = 0; //统计不同值个数
        for (int[] row : origin) {
            for (int col : row) {
                if (col != 0)
                    sum++;
            }
        }
        //创建稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = origin.length; //原行数
        sparseArr[0][1] = origin[0].length; //原列数
        sparseArr[0][2] = sum; //一共不同的数据个数
        //赋值不同的值进入稀疏数组
        int srow = 1;
        for (int i = 0; i < origin.length; i++) {
            for (int j = 0; j < origin[0].length; j++) {
                if (origin[i][j] != 0) {
                    sparseArr[srow][0] = i;
                    sparseArr[srow][1] = j;
                    sparseArr[srow][2] = origin[i][j];
                    srow++;
                }
            }
        }
        System.out.println("\n这是稀疏数组");
        for (int[] row : sparseArr) {
            for (int col : row) {
                System.out.printf("%d\t", col);
            }
            System.out.println();
        }

        //从稀疏数组中复原原数组
        int[][] ReSparse = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            ReSparse[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];  //此处注意,个数与脚标区分清楚。
        }
        System.out.println("\n这是复原的稀疏数组");
        for (int[] row : ReSparse) {
            for (int col : row) {
                System.out.printf("%d\t", col);
            }
            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	1	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	

这是稀疏数组
11	11	3	
1	2	1	
2	3	2	
3	4	1	

这是复原的稀疏数组
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	1	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0

# Java # 数据结构