public class SparseArray {
public static void main ( String[ ] args) {
int [ ] [ ] chessArr1 = new int [ 11 ] [ 11 ] ;
int sum = 0 ;
chessArr1[ 1 ] [ 2 ] = 1 ;
chessArr1[ 2 ] [ 3 ] = 2 ;
System. out. println ( "原始二维数组" ) ;
for ( int [ ] data : chessArr1) {
for ( int da : data) {
System. out. printf ( "%d " , da) ;
if ( da != 0 ) {
sum++ ;
}
}
System. out. println ( ) ;
}
int [ ] [ ] sparseArr = new int [ sum + 1 ] [ 3 ] ;
int count = 0 ;
sparseArr[ 0 ] [ 0 ] = chessArr1. length;
sparseArr[ 0 ] [ 1 ] = chessArr1[ 0 ] . length;
sparseArr[ 0 ] [ 2 ] = sum;
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 ( "稀疏数组为:" ) ;
for ( int [ ] data : sparseArr) {
for ( int da : data) {
System. out. printf ( "%d " , da) ;
}
System. out. println ( ) ;
}
File f = new File ( "./dataStructure/chess.txt" ) ;
if ( ! f. exists ( ) ) {
try {
f. createNewFile ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
try {
FileWriter fw = new FileWriter ( f) ;
for ( int [ ] data : sparseArr) {
for ( int da : data) {
fw. write ( da+ " " ) ;
}
fw. write ( "\n" ) ;
}
fw. close ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
try {
InputStreamReader isr = new InputStreamReader ( new FileInputStream ( f) ) ;
BufferedReader br = new BufferedReader ( isr) ;
String line1 = null;
if ( ( line1 = br. readLine ( ) ) != null) {
String[ ] line = line1. split ( " " ) ;
int [ ] [ ] chessArr2 = new int [ Integer. valueOf ( line[ 0 ] ) ] [ Integer. valueOf ( line[ 1 ] ) ] ;
int rowCount = Integer. valueOf ( Integer. valueOf ( line[ 2 ] ) ) ;
while ( rowCount > 0 ) {
line = br. readLine ( ) . split ( " " ) ;
chessArr2[ Integer. valueOf ( line[ 0 ] ) ] [ Integer. valueOf ( line[ 1 ] ) ] = Integer. valueOf ( line[ 2 ] ) ;
rowCount-- ;
}
System. out. println ( "恢复二维数组" ) ;
for ( int [ ] data : chessArr2) {
for ( int da : data) {
System. out. printf ( "%d " , da) ;
}
System. out. println ( ) ;
}
br. close ( ) ;
isr. close ( ) ;
}
} catch ( FileNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
原始二维数组
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
稀疏数组为:
11 11 2
1 2 1
2 3 2
恢复二维数组
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
Process finished with exit code 0