package SparseArray;
public class SparseArray {
private int [][] chess_array ;
public int [][] sparse_array;
private int n;
public SparseArray() {}
public void setchess_array(int [][] chess_array) {
this.chess_array = chess_array;
}
public void setparse_array(int [][] sparse_array){
this.sparse_array=sparse_array;
}
public int [][] getchess_array() {
return chess_array;
}
public int [][] getsparse_array(){
return sparse_array;
}
public void setn(int n) {
this.n = n;
}
public int getn() {
return n;
}
public int [][] chess_array_to_sparse_array() {
int row = chess_array.length;
int col = chess_array[0].length;
//数组在Java中必须在声明时指定大小,或者在使用时直接初始化,才能赋值
int count = 0;
for(int r = 0; r < row; r++) {
for(int c = 0; c < col; c++) {
if(chess_array[r][c] !=n) {
count++;
}
}
}
int [] [] sparse_array=new int [count+1][3];
int s=0;
for(int r = 0; r < row; r++) {
for(int c = 0; c < col; c++) {
if(chess_array[r][c] !=n) {
s++;
sparse_array[s][0]=r;
sparse_array[s][1]=c;
sparse_array[s][2]=chess_array[r][c];
}
}
}
sparse_array[0][0]=row;
sparse_array[0][1]=col;
sparse_array[0][2]=count;
return sparse_array;
}
}
———————————————————————————————————————————
package SparseArray;
public class Main {
public static void main(String[] args) {
int [] [] array={{0,0,10,0,0,0,0}, {0,4,0,0,0,0,0},{7,0,0,0,0,0,0}
};
SparseArray to =new SparseArray();
to.setchess_array(array);
to.setn(0);
int [][] spare = to.chess_array_to_sparse_array();
int row= spare.length;
int clo=spare[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<clo;j++){
System.out.print(spare[i][j]);
System.out.print("|");
}
System.out.println();
}
}
}
这个是二维数组转稀疏数组,注意有两次遍历!!!因为数组的长度是不可以改变的