稀疏数组
- 遍历二维数组 ,计数非0值个数为sum++
int sum = 0;
for (int i = 0;i< chessArr.length;i++){
for (int j = 0;j< chessArr.length;j++){
if (chessArr[i][j] != 0){
sum++;
}
}
}
- 创建SparseArray , row为sum+1 , column为3
int sparseArr[][] = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
3.采用遍历二维数组的方式将值插入到稀疏数组中
int count = 0;//计数非0值个数
for (int i = 0;i< chessArr.length;i++){
for (int j = 0;j< chessArr.length;j++){
if (chessArr[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr[i][j];
}
}
}
4.格式化输出稀疏数组
System.out.println("稀疏数组为~~~~");
for (int i = 0; i<sparseArr.length;i++){
System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
}
5.复原稀疏数组的值到二维数组中
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1;i<sparseArr.length;i++){
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
全代码如下:
public class SparseArray {
//假设用稀疏数组和二维数组存档五子棋游戏的黑子和白子落棋位置
public static void main(String[] args) {
int chessArr[][] = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][3] = 2;
chessArr[4][5] = 2;
for (int[] row : chessArr) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println("");
}
int sum = 0;
for (int i = 0; i < chessArr.length; i++) {
for (int j = 0; j < chessArr.length; j++) {
if (chessArr[i][j] != 0) {
sum++;
}
}
}
System.out.println(sum);
int sparseArr[][] = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
int count = 0;
for (int i = 0; i < chessArr.length; i++) {
for (int j = 0; j < chessArr.length; j++) {
if (chessArr[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr[i][j];
}
}
}
System.out.println("");
System.out.println("稀疏数组为~~~~");
for (int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
}
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
for (int[] row : chessArr2) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println("");
}
}
}