稀疏矩阵
public class sparseArray {
public static void main(String[] args) {
int[][] a = new int[6][7];
a[1][1] = 1;
a[2][2] = 2;
a[3][3] = 3;
for(int[] row:a){
for (int data:row) {
System.out.print(data +" ");
}
System.out.println();
}
int sum = 0;
for(int i = 0;i<a.length;i++){
for(int j =0 ;j<a[0].length;j++){
if(a[i][j]!=0){
sum++;
}
}
}
System.out.println("将二维数组转换为稀疏矩阵");
int[][] sparseArr = new int[sum+1][3];
sparseArr[0][0] = a.length;
sparseArr[0][1] = a[0].length;
sparseArr[0][2] = sum;
int num = 1;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
if(a[i][j]!= 0){
sparseArr[num][0] = i;
sparseArr[num][1] = j;
sparseArr[num][2] = a[i][j];
num++;
}
}
}
for(int[] row:sparseArr){
for (int data:row) {
System.out.print(data +" ");
}
System.out.println();
}
System.out.println("将稀疏矩阵转换为二维数组");
int[][] b = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
b[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
for(int[] row:b){
for (int data:row) {
System.out.print(data +" ");
}
System.out.println();
}
}
}
|