问题引起:棋盘问题
思路:
1.创建二维数组并进行赋值统计数据个数
public int twoDimensionalArray(){ int sum = 0; arr[2][5] = 1; arr[3][6] = 2; arr[4][8] = 3; arr[5][3] = 4; arr[6][1] = 5; arr[7][0] = 6; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j]+" "); int value = arr[i][j]; if (value !=0) sum +=1; } System.out.println(); } return sum; }
2.二维数组转稀疏数组
思路分析:
1.统计二维数组的值的个数sum,根据sum创建稀疏数组 new int[sum+1][3]
2.获得二位数的行数row和列数column,连同sum保存到稀疏数组的第一行
3.遍历二维数组,获取二维数组的值(value)的行(row)和列(column)将其作为一个数组保存的稀疏数组的一行中
arrSparse[k][0] = i;
arrSparse[k][1] = j;
arrSparse[k][2] = sparevalue;
4.遍历显示稀疏数组
public int[][] toSparseArray(){ int sum = twoDimensionalArray(); int row = arr.length; int column = arr[0].length; int value = sum; int[][] arrSparse = new int[sum+1][3]; arrSparse[0][0] = row; arrSparse[0][1] = column; arrSparse[0][2] = value; int k = 1; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { int sparevalue = arr[i][j]; if (sparevalue !=0){ arrSparse[k][0] = i; arrSparse[k][1] = j; arrSparse[k][2] = sparevalue; k+=1; } } } showArray(arrSparse); return arrSparse; }
3.稀疏数组转二维数组
思路分析:
1.获取稀疏数组的第0行数据,行 row = arr[0][0], 列column = arr[0][1]
2.根据行和列创建二维数组 new int[row][column]
3.遍历稀疏数组,将值赋值到对应的二维数组位置
int a = arr[i][0];
int b = arr[i][1];
int c = arr[i][2];
twoSparesArray[a][b] = c;
4.显示转换后的二位数组
public void toTwoSparseArray(int[][] arr){ int row = arr[0][0]; int column = arr[0][1]; int sum = arr[0][2]; int rowk = 1; int[][] twoSparesArray = new int[row][column]; for (int i = 1; i < arr.length; i++) { int a = arr[i][0]; int b = arr[i][1]; int c = arr[i][2]; twoSparesArray[a][b] = c; rowk += 1; } showArray(twoSparesArray); } /* * 遍历数组 * */ public void showArray(int[][] arr){ for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } }