*spiral Matrix

Source: Internet
Author: User

title :

Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X in Spiral Order.

For example,
Given the following matrix:

[[1, 2, 3],[4, 5, 6],[7, 8, 9]]

You should return [1,2,3,6,9,8,7,4,5] .

The following:
This problem is a realization problem.

Consider 2 initial conditions, if the matrix has only one row or column, then you do not need to rotate, then output.

All other situations need to be in circles: from left to right, from top to bottom, right to left, bottom to top. Loop from the big circle to the small circle in turn.

The code is as follows:

1  PublicArraylist<integer> Spiralorder (int[] matrix) {2arraylist<integer> result =NewArraylist<integer>();3         if(Matrix = =NULL|| Matrix.length = = 0)4             returnresult;5  6         intm =matrix.length;7         intn = matrix[0].length;8  9         intX=0; Ten         intY=0; One   A          while(M>0 && n>0){ -   -             //if one row/column left, no circle can be formed the             if(m==1){ -                  for(inti=0; i<n; i++){ -Result.add (matrix[x][y++]); -                 } +                  Break; -}Else if(n==1){ +                  for(inti=0; i<m; i++){ AResult.add (matrix[x++][y]); at                 } -                  Break; -             } -   -             //below, process a circle -   in             //Top-move Right -              for(inti=0;i<n-1;i++) toResult.add (matrix[x][y++]); +   -             //Right-move Down the              for(inti=0;i<m-1;i++) *Result.add (matrix[x++][y]); $  Panax Notoginseng             //Bottom-move Left -              for(inti=0;i<n-1;i++) theResult.add (matrix[x][y--]); +   A             //Left-move up the              for(inti=0;i<m-1;i++) +Result.add (matrix[x--][y]); -   $X + +; $y++; -M=m-2; -N=n-2; the         } -  Wuyi         returnresult; the}

Reference:http://www.cnblogs.com/springfor/p/3887890.html

*spiral 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.