Mutual conversion of two-dimensional arrays and sparse arrays

struct Package; 

public class SparseArr {
public static void main (String [] args) {
int Chess [] [] = new new int [. 11] [. 11];
// 0 representatives blank, a representative of sunspots, represents blue sub
Chess [ . 1] [2] =. 1;
Chess [2] [. 3] = 2;
int SUM = 0;
// Get the number of valid
for (int [] rows: Chess) {
for (int Data: rows) {
the System. form out.printf ( "% D \ T", Data);
IF (Data = 0!) {
SUM ++;
}
}
System.out.println ();
}
// create a sparse array
int [] [] sparseArr = new int [ . 1 + SUM] [. 3];
// to sparse array assignment
sparseArr [0] [0] = 11; // Number of rows of the board
sparseArr [0] [1] = 11; // number of columns of the board
sparseArr [0] [2] = sum; // number of pieces on the board
// length of two-dimensional array of rows
int = COUNT. 1;
for (int I = 0; I <chess.length; I ++) {
for (int J = 0; J <Chess [0] .length; J ++) {
IF (Chess [I] [J] = 0!) {
sparseArr [COUNT] [0] = I;
sparseArr [COUNT] [. 1] = J;
sparseArr [COUNT] [2] = Chess [I] [J];
++ COUNT;
}
}
}
// output sparse array
for (int i = 0; i <sparseArr.length; i ++) {
System.out.printf ( "% D \ D% T \ T% D \ T \ n-", sparseArr [I] [0], sparseArr [I] [. 1], sparseArr [I] [2]);
}
/ / restore dimensional array
int [] [] = chess1Arr new new int [sparseArr [0] [0]] [sparseArr [0] [. 1]];
// assignment to a two-dimensional array
for (int i = 1; i <sparseArr .length; I ++) {
for (int J = 0; J <sparseArr [0] .length; J ++) {
chess1Arr [sparseArr [I] [0]] [sparseArr [I] [. 1]] = sparseArr [I] [ 2];
}
}
// output two-dimensional array
for (int I = 0; I <chess1Arr.length; I ++) {
for (int J = 0; J <chess1Arr [0] .length; J ++) {
the System.out. the printf ( "% D \ T", chess1Arr [I] [J]);
}
System.out.println();
}
}
}

Guess you like

Origin www.cnblogs.com/kukai/p/10992004.html