代码实现:
1 public class SparseArray { 2 3 public static void main(String[] args) { 4 5 //创建一个原始的二维数组11*11 6 //1表示黑子,2表示白子,三表示没有棋子 7 int[][] chessArr1 = new int[11][11]; 8 chessArr1[1][2] = 1; 9 chessArr1[2][3] = 2; 10 //输出原始数组 11 for (int[] ints : chessArr1) { 12 for (int anInt : ints) { 13 System.out.print(anInt + " "); 14 } 15 System.out.println(); 16 } 17 //将二维数组转换为稀疏数组 18 //1.先遍历二维数组得到非0数据的个数 19 int sum = 0; 20 for (int i = 0; i < chessArr1.length; i++) { 21 for (int j = 0; j < chessArr1[0].length; j++) { 22 if (chessArr1[i][j] != 0){ 23 sum++; 24 } 25 } 26 } 27 System.out.println("sum="+sum); 28 //2.根据sum的值创建对应的数组 29 int[][] sparseArr = new int[sum + 1][3]; 30 sparseArr[0][0] = chessArr1.length; 31 sparseArr[0][1] = chessArr1[0].length; 32 sparseArr[0][2] = sum; 33 //遍历二维数组将非零的值存放到稀疏数组中 34 int count = 0;//用于计数,记录是第几个非零数据 35 for (int i = 0; i < chessArr1.length; i++) { 36 for (int j = 0; j < chessArr1[0].length; j++) { 37 if (chessArr1[i][j] != 0){ 38 count++; 39 sparseArr[count][0] = i; 40 sparseArr[count][1] = j; 41 sparseArr[count][2] = chessArr1[i][j]; 42 } 43 } 44 } 45 //输出稀疏数组的形式 46 System.out.println("得到的稀疏数组为以下形式:"); 47 for (int[] ints : sparseArr) { 48 for (int anInt : ints) { 49 System.out.print(anInt + " "); 50 } 51 System.out.println(); 52 } 53 54 //将稀疏数组恢复成原始的二维数组 55 //1.先读取稀疏数组第一行,根据其第一行来得到原数组的行和列 56 int row = sparseArr[0][0]; 57 int cos = sparseArr[0][1]; 58 int[][] chessArr2 = new int[row][cos]; 59 //2.读取稀疏数组,赋值 60 for (int i = 1; i < sparseArr.length; i++) { 61 chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2]; 62 } 63 64 System.out.println("还原的数组为以下形式:"); 65 for (int[] ints : chessArr2) { 66 for (int anInt : ints) { 67 System.out.print(anInt + " "); 68 } 69 System.out.println(); 70 } 71 } 72 73 74 }