Title:
Given a matrix, the matrix is printed in the form of a glyph. For example:
1 2 3 4
5 6 7 8
9 10 11 12
The result of the glyph print is: 1,2,5,9,6,3,4,7,10,11,8,12
Additional space complexity is required for O (1).
Ideas:
1. The upper coordinate (TR,TC) is initially (0,0), moving along the first row of the matrix (tc++), when the rightmost element of the first line is reached, and then moves along the last column of the Matrix (tr++).
2. The lower coordinate (DR,DC) is initially (0,0), first moving along the first column of the Matrix (dr++), and when it reaches the bottom element of the first column, it must Be (dc++) along the last line of the matrix.
3. The upper and lower coordinates are moved synchronously, and the line between the upper and lower coordinates after each move is a slash in the matrix, and the elements on the diagonal are printed.
4. If the last slash was printed from lower left to right, this time it must be printed from top to left and vice versa. In short, you can use the direction of printing as a Boolean variable, each time you take the reverse.
Program:
Public Static voidPrintmatrixzigzag (int[] matrix) { intTC = 0, TR = 0, DC = 0, DR = 0; intEndr = matrix.length-1; intENDC = matrix[0].length-1; BooleanFromup =false; while(TR! = Endr + 1) {printlevel (Matrix, TR, TC, DR, DC, Fromup); TR= TC = = Endc? TR + 1: TR; TC= TC = = Endc? TC:TC + 1; DC= DR = = Endr? DC + 1: DC; DR= DR = = Endr? DR:DR + 1; Fromup= !Fromup; } } Private Static voidPrintlevel (int[] Matrix,intTrintTcintDR,intDC,Booleanfromup) { if(fromup) { while(TR! = DR + 1) {System.out.print (matrix[tr++][tc--] + ""); } } Else { while(DR! = tR-1) {System.out.print (Matrix[dr--][dc++] + ""); } } }
[Algorithm] "Zigzag print matrix"