如图:
public class App { public static void main( String[] args ) { int[][] checkerboard = new int[11][11]; //原始数组 checkerboard[1][2]=1; checkerboard[2][3]=2; int [][] sparseArray=transtoSparseArray(checkerboard); System.out.println("原始数组。。。。。。。。。。"); printArray(checkerboard); System.out.println("稀疏数组。。。。。。。。。。"); printArray(sparseArray); System.out.println("稀疏数组转原始数组。。。。。。。。。。"); printArray(transToPlainArray(sparseArray)); } private static void printArray(int[][] sparseArray){ for (int[] arr : sparseArray) { for (int i : arr) { System.out.print(i); System.out.print(" "); } System.out.println(""); } } private static int[][] transtoSparseArray(int[][] plainArray){ int sum=0; for (int[] rows : plainArray) { for (int row : rows) { if(row!=0){ sum++; } } } //稀疏数组 int[][] sparseArray = new int[sum + 1][3]; sparseArray[0][0]=11; sparseArray[0][1]=11; sparseArray[0][2]=sum; int row=1; for (int i = 0; i < plainArray.length; i++) { int[] arr=plainArray[i]; for (int j = 0; j < arr.length; j++) { int k=arr[j]; if(k!=0){ sparseArray[row][0]=i; sparseArray[row][1]=j; sparseArray[row][2]=k; row++; } } } return sparseArray; } private static int[][] transToPlainArray(int[][] sparseArray){ //稀疏数组转普通数组 int row = sparseArray[0][0]; int cl = sparseArray[0][1]; int[][] plainArrays = new int[row][cl]; for (int i = 1; i < sparseArray.length; i++) { int[] arr=sparseArray[i]; for (int j = 0; j < arr.length; j++) { int r=arr[0]; int c=arr[1]; int v=arr[2]; plainArrays[r][c]=v; } } return plainArrays; } }
测试结果: