编程语言
首页 > 编程语言> > Java数据结构与算法(一)

Java数据结构与算法(一)

作者:互联网

 稀疏矩阵转为压缩矩阵

减少其他数组个数的浪费

public class SparseChess {
    public  static void main(String[]args){
        //新建一个稀疏矩阵(11*11)黑子为1 白子为2
        int [][]chess=new int[11][11];
        chess[1][3]=1;
        chess[2][4]=2;
        System.out.println("稀疏矩阵");
        for (int [] raws:chess
             ) {
            for (int date:raws
                 ) {

                System.out.printf("%d\t",date);
            }
            System.out.println();

        }
        //统计在稀疏矩阵中有值得数组个数
        int sum=0;
        for (int cc = 0; cc <chess.length ; cc++) {
            for (int c = 0; c <chess.length; c++) {
                if (chess[cc][c]!=0) {
                    sum++;

                }

            }

        }
        System.out.printf("数组中有值得个数"+"%d",sum);
        //新矩阵用来存值,第一行存稀疏矩阵大小和个数,
        int chess2[][]=new int[sum+1][3];
        chess2[0][0]= chess.length;
        int s=1;
        chess2[0][1]=chess[chess.length-1].length;
        chess2[0][2]=sum;
        for (int cc = 0; cc <chess.length ; cc++) {
            for (int c = 0; c <chess.length; c++) {
                if (chess[cc][c]!=0) {
                    chess2[s][0]=cc;
                    chess2[s][1]=c;
                 chess2[s][2]=chess[cc][c];
                 s++;

                }

            }

        }
        //讲压缩矩阵打印出来
        System.out.println("压缩矩阵");

        for (int[] rows:chess2
             ) {
            for (int data:rows
                 ) {
                System.out.printf("%d\t",data);

            }
            System.out.println();

        }
        //还原成稀疏矩阵
        int [][]chess3=new int[chess2[0][0]][chess2[0][1]];
        for (int s1 = 1; s1 < chess2.length; s1++) {

                chess3[chess2[s1][0]][chess2[s1][1]]=chess2[s1][2];
                System.out.println(chess2[s1][2]);




        }
        for (int []raw:chess3
             ) {
            for (int data:raw
                 ) {
                System.out.printf("%d\t",data);

            }
            System.out.println();

        }

    }

}

标签:11,Java,int,矩阵,System,算法,chess,数据结构,out
来源: https://blog.csdn.net/m0_50217592/article/details/122369049