标签:str pac auth public 存储 pack out 代码 void
代码如下:package com.atguigu.sparsearray;
/**
* @author ChenDan
* @date 2019/7/20 10:52
*/
public class SparseArray {
public static void main(String[] args) {
//创建一个原始的二维数组 11*11
//0表示没有棋子,1表示黑子,2表示蓝子
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[4][5] = 2;
System.out.println("原始的二维数组~~");
for (int[] row : chessArr1) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
//将二维数组转换为稀疏数组
//先遍历二维数组得到非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; //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];
}
}
}
//输出稀疏数组形式
System.out.println();
System.out.println("得到的稀疏数组为~~~~");
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < sparseArr[i].length; j++) {
System.out.printf("%d\t", sparseArr[i][j]);
}
System.out.println();
}
//将稀疏数组恢复为原始的二维数组
//1.读取稀疏数组的第一行得到二维数组的索引
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
//2.读取后几行(从稀疏数组的第二行开始)稀疏数组,并赋值给恢复的二维数组
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
//恢复后的二维数组
System.out.println();
System.out.println("恢复后的二维数组~~");
for (int i = 0; i < chessArr2.length; i++) {
for (int j = 0; j < chessArr2[i].length; j++) {
System.out.printf("%d\t", chessArr2[i][j]);
}
System.out.println();
}
}
}
标签:str pac auth public 存储 pack out 代码 void
原文地址:https://blog.51cto.com/9447803/2422009