编程语言
首页 > 编程语言> > 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]));
        }
    }
}

标签:Java,int,矩阵,稀疏,++,length,sparse,array,out
来源: https://www.cnblogs.com/lu-longhui/p/15635968.html