Leetcode's Spiral Matrix

Source: Internet
Author: User

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] .

This problem thought for a long time did not think up, can only blame oneself too lazy, lazy to think to try, should calm down heart to not too impetuous.

There are four kinds of cases, from left to right, top to bottom, right to left, and bottom up.

Careful observation found that it was possible to make use of changes in Rowresult and Columnresult.

Put the code below, be sure to note that the

int row = Matrix.length;
int column = Matrix[0].length; before judging if the matrix is empty. So that the column does not go wrong.

The code is as follows:

public class Solution {public list<integer> spiralorder (int[][] matrix) {list<integer> Listresult        = new Arraylist<integer> ();        if (Matrix = = NULL | | matrix.length==0) {return listresult;        } int row = Matrix.length;        int column = Matrix[0].length;        int rowNumber = 0;        int columnnumber = 0; while (row>0&&column>0) {if (row = = 1) {for (int i = 0;i<column;i++) {Listresult.add (ma        trix[rownumber][columnnumber++]);        } break; } else {if (column = = 1) {for (int i = 0;i<row;i++) {Listresult.add (matrix[rownumber++][            ColumnNumber]);        } break;        }} for (int i = 0;i<column-1;i++) {listresult.add (matrix[rownumber][columnnumber++]);        }//columnnumber = columnNumber-1;    for (int i = 0;i<row-1;i++) {listresult.add (Matrix[rownumber++][columnnumber]);    }//rownumber = rowNumber-1;        for (int i = 0;i<column-1;i++) {listresult.add (matrix[rownumber][columnnumber--]);        }//columnnumber = ColumnNumber + 1;        for (int i =0;i<row-1;i++) {Listresult.add (Matrix[rownumber--][columnnumber]);        } rownumber++;        columnnumber++;        row = Row-2;        column = Column-2;    } return Listresult; }}

  

Leetcode's 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.