1. 程式人生 > 其它 >Java程式碼實現稀疏矩陣

Java程式碼實現稀疏矩陣

/**
 * @description: 稀疏陣列
 * @author: Leon
 * @date: 2021/12/2 22:29
 **/
public class Sparse {
    public static void main(String[] args) {
        int[][] array = new int[10][10];
        array[1][3] = 1;
        array[2][4] = 2;
        //列印陣列
        for (int i = 0; i < array.length; i++) {
            System.out.println(Arrays.toString(array[i]));
        }
        System.out.println("----------------------------------------------");
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    sum++;
                }
            }
        }
        System.out.println("sum=" + sum);
        int[][] sparse = new int[sum + 1][3];
        // 儲存之前陣列的行數i
        sparse[0][0] = 10;
        // 儲存之前陣列的列數j
        sparse[0][1] = 10;
        // 儲存之前陣列初始化的值
        sparse[0][2] = 0;
        System.out.println("----------------------------------------------");
        // 構建稀疏陣列
        int number = 0;
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                if (array[i][j] != 0) {
                    number++;
                    sparse[number][0] = i;
                    sparse[number][1] = j;
                    sparse[number][2] = array[i][j];
                }
            }
        }
        // 輸出稀疏陣列
        for (int i = 0; i < sparse.length; i++) {
            System.out.println(Arrays.toString(sparse[i]));
        }
        System.out.println("----------------------------------------------");
        // 稀疏陣列轉普通陣列
        // 獲取行數i
        int iLength = sparse[0][0];
        // 獲取長度j
        int jLength = sparse[0][1];
        int[][] ordinary = new int[iLength][jLength];
        // 賦初值
        for (int i = 0; i < ordinary.length; i++) {
            for (int j = 0; j < ordinary[i].length; j++) {
                // 賦初值
                ordinary[i][j] = sparse[0][2];
            }
        }
        for (int i = 1; i < sparse.length; i++) {
            // 拿到當前行數
            int iSpace = sparse[i][0];
            // 拿到當前列數
            int jSpace = sparse[i][1];
            // 拿到當前位置的值
            int value = sparse[i][2];
            ordinary[iSpace][jSpace] = value;
        }
        // 輸出由稀疏矩陣轉換而來的陣列
        for (int i = 0; i < ordinary.length; i++) {
            System.out.println(Arrays.toString(ordinary[i]));
        }
    }
}