步骤:
1.创建一个11*11的原数组,并初始化;遍历输出
int chessArr1[][] = new int[11][11];
// 分别给指定坐标赋值
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][4] = 3;
chessArr1[4][5] = 4;
System.out.println("原始的二维数组");
// 遍历输出
for(int[] row:chessArr1){
for(int date:row){
System.out.printf("%d ",date);
}
System.out.printf("\n\n");
}
2.再算得原数组里不为0的数有几个(这里的sum就是原数组中不为0的数的个数)
// 得到稀疏数组的行
int sum = 0;
for(int i = 0;i<11;i++){
for(int j = 0;j<11;j++){
if(chessArr1[i][j]!=0){
sum++;
}
}
}
3.创建一个行为sum+1,列为3的稀疏数组
int sqarr[][] = new int[sum+1][3];
4.稀疏数组的第一行存的是原数组的行数和列数还有;原数组里有几个值
sqarr[0][0] = 11;
sqarr[0][1] = 11;
sqarr[0][2] = sum;
5.筛选原数组里不为0的行 i 和 j 并赋给稀疏数组 (稀疏数组里最后一列存的是原数组的值,除第一行外)
int count = 0;
for(int i = 0;i<chessArr1.length;i++){
for(int j = 0;j<chessArr1.length;j++){
if(chessArr1[i][j]!=0){
count++;
sqarr[count][0] = i;
sqarr[count][1] = j;
sqarr[count][2] = chessArr1[i][j];
}
}
}
6.遍历输出创建并赋值好的稀疏数组
// 遍历稀疏数组
for(int j = 0;j<sqarr.length;j++){
System.out.printf("%d\t%d\t%d\t\n",sqarr[j][0],sqarr[j][1],sqarr[j][2]);
}
再将稀疏数组转换回原数组
// 将稀疏数组转换为原数组
int chessArr2[][] = new int[sqarr[0][0]][sqarr[0][1]];
// 给原数组指定位置赋值
for(int i = 1;i<sqarr.length;i++){
chessArr2[sqarr[i][0]][sqarr[i][1]] = sqarr[i][2];
}
for(int[] row:chessArr2){
for(int date:row){
System.out.printf("%d ",date);
}
System.out.printf("\n\n");
}
原代码块
public class sqareArray {
// private static String x;
public static void main(String[] args) {
// 创建一个数组
int chessArr1[][] = new int[11][11];
// 分别给指定坐标赋值
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[3][4] = 3;
chessArr1[4][5] = 4;
System.out.println("原始的二维数组");
// 遍历输出
for(int[] row:chessArr1){
for(int date:row){
System.out.printf("%d ",date);
}
System.out.printf("\n\n");
}
// 得到稀疏数组的行
int sum = 0;
for(int i = 0;i<11;i++){
for(int j = 0;j<11;j++){
if(chessArr1[i][j]!=0){
sum++;
}
}
}
// 创建稀疏数组
int sqarr[][] = new int[sum+1][3];
// 给稀疏数组赋值
sqarr[0][0] = 11;
sqarr[0][1] = 11;
sqarr[0][2] = sum;
int count = 0;
for(int i = 0;i<chessArr1.length;i++){
for(int j = 0;j<chessArr1.length;j++){
if(chessArr1[i][j]!=0){
count++;
sqarr[count][0] = i;
sqarr[count][1] = j;
sqarr[count][2] = chessArr1[i][j];
}
}
}
// int chessArr2[][] = new int[sqarr[0][0]][]
// 遍历稀疏数组
for(int j = 0;j<sqarr.length;j++){
System.out.printf("%d\t%d\t%d\t\n",sqarr[j][0],sqarr[j][1],sqarr[j][2]);
}
// 将稀疏数组转换为原数组
int chessArr2[][] = new int[sqarr[0][0]][sqarr[0][1]];
// 给原数组指定位置赋值
for(int i = 1;i<sqarr.length;i++){
chessArr2[sqarr[i][0]][sqarr[i][1]] = sqarr[i][2];
}
for(int[] row:chessArr2){
for(int date:row){
System.out.printf("%d ",date);
}
System.out.printf("\n\n");
}
}
}