二维数组与稀松数组之间转换
public class Test1 { public static void main(String[] args) { int arr1[][]=new int[10][10]; arr1[1][1]=1; arr1[2][3]=2; arr1[4][2]=1; System.out.println("原始二维数组"); for (int[] row:arr1 ) { for (int data:row ) { System.out.printf("%d\t",data); } System.out.println(); } int sum=0; for (int i = 0; i <10 ; i++) { for (int j = 0; j <10 ; j++) { if (arr1[i][j]!=0){ sum++; } } } //稀松数组 System.out.println("稀松数组"); int sarr[][]=new int[sum+1][3]; sarr[0][0]=10; sarr[0][1]=10; sarr[0][2]=sum; int count=0; for (int i = 0; i <10 ; i++) { for (int j = 0; j <10 ; j++) { if (arr1[i][j]!=0){ count++; sarr[count][0]=i; sarr[count][1]=j; sarr[count][2]=arr1[i][j]; } } } for (int[] row:sarr ) { for (int data:row ) { System.out.printf("%d\t",data); } System.out.println(); } System.out.println("稀松转二维"); int arr2[][]=new int[sarr[0][0]][sarr[0][1]]; for (int i = 1; i <sarr.length ; i++) { arr2[sarr[i][0]][sarr[i][1]]=sarr[i][2]; } for (int[] row:arr2 ) { for (int data:row ) { System.out.printf("%d\t",data); } System.out.println(); } } }
输出如下 原始二维数组 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 稀松数组 10 10 3 1 1 1 2 3 2 4 2 1 稀松转二维 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0