[Algorithm] "Zigzag print matrix"

Source: Internet
Author: User

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"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.