//创建一个原始的二维数组11*11,0表示无子,1表示黑子,2表示蓝子
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
//输出原始二维数组
for (int[] row : chessArr1){
for (int data : row){
System.out.print(data + "\t");
System.out.println();
}
2、将二维数组转换为稀疏数组
//将二维数组转换为稀疏数组
//先遍历二维数组,得到非0数据的个数
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) 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 < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[i].length; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
//输出稀疏数组
for (int[] row : sparseArr){
for (int data : row){
System.out.print(data + "\t");
System.out.println();
}
3、将稀疏数组转回二维数组
//将稀疏数组转换为二维数组
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.print(data + "\t");
System.out.println();