关于稀疏数组
二维数组 转 稀疏数组的思路
- 遍历 原始的二维数组,得到有效数据的个数 sum
- 根据sum 就可以创建 稀疏数组 sparseArr int[sum + 1] [3]
- 将二维数组的有效数据数据存入到 稀疏数组
稀疏数组转原始的二维数组的思路
- 先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组
2.再将稀疏数组中后几行数据赋给原始数组
五子棋棋盘的问题
上代码:
public class SparseArray {
public static void main(String[] args) {
//先创建一个二维数组 11*11
//0:表示无棋子,1:表示黑棋,2:表示白棋
int chessArry1[][] =new int[11][11];
chessArry1[1][2]=1;
chessArry1[2][3]=2;
chessArry1[3][3]=2;
//输出原始二维数组
System.out.println("原来的二维数组:");
for(int[] row :chessArry1) { //遍历每行的二维数组用row一维数组记录
for(int data:row) { //遍历row用data记录数据
System.out.printf("%d\t",data);
}
System.out.println();
}
/*
* 将二维数组转换为稀疏数组
* 1.先遍历二维数组得到有几个有效值sum和行列个数
* 2.根据sum创建稀疏数组 sparseArr[sum+1][3]
* 3.将二维数组有效值存在稀疏数组中
* */
//一般情况下不知道二维数组行列,用两值来记录
int c_row=0; //记录列个数
int c_all=0; //记录二维数组所有个数用于记录列个数
//1.先遍历二维数组得到有几个有效值sum和行列
int sum=0;
for(int[] row :chessArry1) {
c_row++;
for(int data:row) {
c_all++;
if(data!=0) { //如果原二维数组不为零 sum就加1
sum++;
}
}
}
int c_col=c_all/c_row;//得到列个数
System.out.println("sum="+sum);
System.out.println("原二维数组的行为:"+c_row);
System.out.println("原二维数组的列为:"+c_col);
//2.根据sum创建稀疏数组 sparseArr[sum+1][3]
int sparseArr[][] =new int[sum+1][3];
sparseArr[0][0]=c_row;
sparseArr[0][1]=c_col;
sparseArr[0][2]=sum;
//3.将二维数组有效值存在稀疏数组中
int count =0; //count用于记录是第几个非零数据
for(int i=0;i<c_row;i++) {
for(int j=0;j<c_col;j++) {
if(chessArry1[i][j]!=0) {
count++;
sparseArr[count][0]=i;
sparseArr[count][1]=j;
sparseArr[count][2]=chessArry1[i][j];
}
}
}
System.out.println("得到的稀疏数组为~~~");
for(int[] row :sparseArr) {
for(int data:row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
System.out.println();
/*将稀疏数组转换为原二维数组
* 1.先读取稀疏数组的第一行,根据数据转换为原始二维数组
* 2.再读取稀疏数组后几行数据赋给原始二维数组
* */
int chessArry2[][]= new int[sparseArr[0][0]][sparseArr[0][1]];
for(int i=1;i<sparseArr.length;i++) {
chessArry2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("得到的原二维数组为~~~");
for(int[] row :chessArry2) {
for(int data:row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}