二维数组和稀疏数组的转换

package com.hand.sparseArray;

public class SparseArrayTest {

    public static void main(String[] args) {


        /**
         * 二维数组转稀疏数组的思路
         */
        //遍历原始的二维数组得到有效的数据个数sum

        //根据sum创建稀疏数组sparseArr[sum+1][3]

        //将二维数组的有效数组存入稀疏数组

        int[][] originArray = new int[11][11];

        originArray[1][1] = 1;
        originArray[2][3] = 2;
        originArray[2][4] = 3;

        System.out.println("原始数组:");
        for (int[] row : originArray) {
            for (int i : row) {
                System.out.printf("%d\t", i);
            }
            System.out.println();
        }

        //求sum的值
        int sum = 0;
        for (int i = 0; i < originArray.length; i++) {
            for (int j = 0; j < originArray.length; j++) {
                if (originArray[i][j] != 0) {
                    sum++;
                }
            }
        }

        System.out.println("有效数据个数:" + sum);

        //创建稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        //将二维数组的有效数组存入稀疏数组
        int count = 1;
        for (int i = 0; i < originArray.length; i++) {
            for (int j = 0; j < originArray.length; j++) {
                if (originArray[i][j] != 0) {
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = originArray[i][j];
                    count++;
                }
            }
        }

        System.out.println("稀疏数组:");
        for (int[] row : sparseArray) {
            for (int i : row) {
                System.out.printf("%d\t", i);
            }
            System.out.println();
        }


        /**
         * 稀疏数组转二维数组的思路
         */
        //先读取稀疏数组的第一行 根据第一行去初始化二维数组

        int[][] newArray = new int[sparseArray[0][0]][sparseArray[0][1]];


        //读取稀疏数组的后几行数据 进行依次的赋值

        for (int i = 1; i < sparseArray.length; i++) {
            newArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("稀疏数组 -> 二维数组:");
        for (int[] row : newArray) {
            for (int i : row) {
                System.out.printf("%d\t", i);
            }
            System.out.println();
        }

    }
}

 

你可能感兴趣的:(算法)