二维数组转换为稀疏数组和恢复
package SJJG;
public class SparseArry {
public static void main ( String[ ] args) {
int chessArry1[ ] [ ] = new int [ 11 ] [ 11 ] ;
chessArry1[ 1 ] [ 2 ] = 1 ;
chessArry1[ 2 ] [ 3 ] = 2 ;
chessArry1[ 3 ] [ 4 ] = 2 ;
System. out. println ( "输出原始二维数组~~" ) ;
for ( int [ ] row: chessArry1) {
for ( int data: row) {
System. out. printf ( "%d\t" , data) ;
}
System. out. println ( ) ;
}
int sum = 0 ;
for ( int i= 0 ; i< chessArry1. length; i++ ) {
for ( int j= 0 ; j< chessArry1. length; j++ ) {
if ( chessArry1[ i] [ j] != 0 ) {
sum++ ;
}
}
}
int chessArry2[ ] [ ] = new int [ sum+ 1 ] [ 3 ] ;
chessArry2[ 0 ] [ 0 ] = chessArry1. length;
chessArry2[ 0 ] [ 1 ] = chessArry1. length;
chessArry2[ 0 ] [ 2 ] = sum;
int count = 0 ;
for ( int i= 0 ; i< chessArry1. length; i++ ) {
for ( int j= 0 ; j< chessArry1. length; j++ ) {
if ( chessArry1[ i] [ j] != 0 ) {
count++ ;
chessArry2[ count] [ 0 ] = i;
chessArry2[ count] [ 1 ] = j;
chessArry2[ count] [ 2 ] = chessArry1[ i] [ j] ;
}
}
}
System. out. println ( ) ;
System. out. println ( "输出稀疏数组~~" ) ;
for ( int i= 0 ; i< chessArry2. length; i++ ) {
System. out. printf ( "%d\t%d\t%d\t\n" , chessArry2[ i] [ 0 ] , chessArry2[ i] [ 1 ] , chessArry2[ i] [ 2 ] ) ;
}
System. out. println ( ) ;
int chessArry3[ ] [ ] = new int [ chessArry2[ 0 ] [ 0 ] ] [ chessArry2[ 0 ] [ 1 ] ] ;
for ( int i= 1 ; i< chessArry2. length; i++ ) {
chessArry3[ chessArry2[ i] [ 0 ] ] [ chessArry2[ i] [ 1 ] ] = chessArry2[ i] [ 2 ] ;
}
System. out. printf ( "输出还原后的网络\n" ) ;
for ( int [ ] row: chessArry3) {
for ( int data: row) {
System. out. printf ( "%d\t" , data) ;
}
System. out. println ( ) ;
}
}
}