“之”字形打印矩阵,额外空间复杂度为O(1)
public class e10ZigZagPrintMatrix {
public static void printMatrixZigZag ( int [ ] [ ] matrix) {
int aR= 0 ;
int aC= 0 ;
int bR= 0 ;
int bC= 0 ;
int EndR= matrix. length- 1 ;
int EndC= matrix[ 0 ] . length- 1 ;
boolean fromUp= false ;
while ( aR!= EndR+ 1 ) {
printLevel ( matrix, aR, aC, bR, bC, fromUp) ;
aR= aC== EndC? aR+ 1 : aR;
aC= aC== EndC? aC: aC+ 1 ;
bC= bR== EndR? bC+ 1 : bC;
bR= bR== EndR? bR: bR+ 1 ;
fromUp= ! fromUp;
}
}
public static void printLevel ( int [ ] [ ] m, int tR, int tC, int dR, int dC, boolean fromUp) {
if ( fromUp) {
while ( tR< dR+ 1 ) {
System. out. print ( m[ tR++ ] [ tC-- ] + " " ) ;
}
} else {
while ( dR> tR- 1 ) {
System. out. print ( m[ dR-- ] [ dC++ ] + " " ) ;
}
}
}
public static void main ( String[ ] args) {
int [ ] [ ] matrix = { { 1 , 2 , 3 , 4 } , { 5 , 6 , 7 , 8 } , { 9 , 10 , 11 , 12 } } ;
printMatrixZigZag ( matrix) ;
}
}