package struct;
public class SparseArr {
public static void main(String[] args) {
int chess[][] = new int[11][11];
//0代表空白,1代表黑子,2代表蓝子
chess[1][2] = 1;
chess[2][3] = 2;
int sum = 0;
//获取有效值个数
for (int[] rows : chess) {
for (int data : rows) {
System.out.printf("%d\t", data);
if (data != 0) {
sum++;
}
}
System.out.println();
}
//创建稀疏数组
int[][] sparseArr = new int[sum + 1][3];
//给稀疏数组赋值
sparseArr[0][0] = 11;//棋盘的行数
sparseArr[0][1] = 11;//棋盘的列数
sparseArr[0][2] = sum;//棋盘上的棋子个数
//二维数组的长度为行数
int count = 1;
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[0].length; j++) {
if (chess[i][j] != 0) {
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chess[i][j];
count++;
}
}
}
//输出稀疏数组
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[][] chess1Arr = new int[sparseArr[0][0]][sparseArr[0][1]];
//给二维数组赋值
for (int i = 1; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr[0].length; j++) {
chess1Arr[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
}
//输出二维数组
for (int i = 0; i < chess1Arr.length; i++) {
for (int j = 0; j < chess1Arr[0].length; j++) {
System.out.printf("%d\t", chess1Arr[i][j]);
}
System.out.println();
}
}
}
转载于:https://www.cnblogs.com/kukai/p/10992004.html