public class SpareArray {
    public static void main(String[] args) {
        
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[4][5] = 2;
        
        System.out.println("原始的二维数组: ");
        for(int [] row : chessArr){
          for (int data: row){
              System.out.printf("%d\t",data);
          }
            System.out.println();
        }
        
        
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0){
                    sum++;
                }
            }
        }
        
        int spareArray[][] = new int[sum + 1][3];
        
        spareArray[0][0] = 11;
        spareArray[0][1] = 11;
        spareArray[0][2] = sum;
        
        int count = 0;
        for (int i = 1; i < 11; i++) {
            for (int j = 1; j < 11; j++) {
                if (chessArr[i][j] != 0){
                    count ++ ;
                    spareArray[count][0] = i;
                    spareArray[count][1] = j;
                    spareArray[count][2] = chessArr[i][j];
                }
            }
        }
        
        System.out.println();
        System.out.println("得到的 稀疏数组是:  ");
        for (int i = 0; i < spareArray.length; i++) {
            System.out.printf("%d\t %d\t %d\t\n",spareArray[i][0],spareArray[i][1],spareArray[i][2]);
        }
        
        
        
        int chessArry1 [][] = new int[spareArray[0][0]][spareArray[0][1]];
        
        for (int i = 1; i < spareArray.length; i++) {
            chessArry1[spareArray[i][0]][spareArray[i][1]]  = spareArray[i][2];
        }
        
        
        
        System.out.println("输出恢复后的二维数组:  ");
        for(int [] row : chessArr){
            for (int data: row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }
}
                
                
                
        
    
转载请注明原文地址:https://ipadbbs.8miu.com/read-2528.html