代碼以下:數組
package com.atguigu.sparsearray; /** * @author ChenDan * @date 2019/7/20 10:52 */ public class SparseArray { public static void main(String[] args) { //建立一個原始的二維數組 11*11 //0表示沒有棋子,1表示黑子,2表示藍子 int[][] chessArr1 = new int[11][11]; chessArr1[1][2] = 1; chessArr1[2][3] = 2; chessArr1[4][5] = 2; System.out.println("原始的二維數組~~"); for (int[] row : chessArr1) { for (int data : row) { System.out.printf("%d\t", data); } System.out.println(); } //將二維數組轉換爲稀疏數組 //先遍歷二維數組獲得非0數據的個數 int sum = 0; for (int i = 0; i < chessArr1.length; i++) { for (int j = 0; j < chessArr1[i].length; j++) { if (chessArr1[i][j] != 0) sum++; } } //建立對應的稀疏數組 int sparseArr[][] = new int[sum + 1][3]; //給稀疏數組賦值 sparseArr[0][0] = 11; sparseArr[0][1] = 11; sparseArr[0][2] = sum; int count = 0; //count用於記錄是第幾個非0數據 for (int i = 0; i < chessArr1.length; i++) { for (int j = 0; j < chessArr1[i].length; j++) { if (chessArr1[i][j] != 0) { count++; sparseArr[count][0] = i; sparseArr[count][1] = j; sparseArr[count][2] = chessArr1[i][j]; } } } //輸出稀疏數組形式 System.out.println(); System.out.println("獲得的稀疏數組爲~~~~"); for (int i = 0; i < sparseArr.length; i++) { for (int j = 0; j < sparseArr[i].length; j++) { System.out.printf("%d\t", sparseArr[i][j]); } System.out.println(); } //將稀疏數組恢復爲原始的二維數組 //1.讀取稀疏數組的第一行獲得二維數組的索引 int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]]; //2.讀取後幾行(從稀疏數組的第二行開始)稀疏數組,並賦值給恢復的二維數組 for (int i = 1; i < sparseArr.length; i++) { chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; } //恢復後的二維數組 System.out.println(); System.out.println("恢復後的二維數組~~"); for (int i = 0; i < chessArr2.length; i++) { for (int j = 0; j < chessArr2[i].length; j++) { System.out.printf("%d\t", chessArr2[i][j]); } System.out.println(); } } }