Leetcode--spiral Matrix

Source: Internet
Author: User

Title: Given a matrix of m x n elements (m rows, n columns), return all elements of the MA Trix 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] .

Note: It is spiral, not s-shaped!

Characteristics: Each time the movement, either the row does not change, or the column does not change;

Code idea is very good!!!

Code:

Package Leetcode;

Import java.util.ArrayList;
Import java.util.List;

public class Correctspiralmatrix {

public static list<integer> Spiralorder (int[][] matrix) {
list<integer> list = new arraylist<> ();
if (Matrix = = NULL | | Matrix.length < 1) {
return list;
}
int m = matrix.length;
int n = matrix[0].length;
if (m = = 1 && n = = 1) {
List.add (Matrix[0][0]);
return list;
}
int dir = 0;
int top = 0, right = n-1, left = 0, buttom = m-1; The corresponding number of rows, the number of columns should be consistent;

while (top <= buttom && left <= right) {//0,1,2,3 stands for four directions!
if (dir = = 0) {
for (int i = left, I <= right; i++) {
List.add (Matrix[top][i]);
}
top++;
}
if (dir = = 1) {
for (int i = top; I <= buttom; i++) {
List.add (Matrix[i][right]);
}
right--;
}

if (dir = = 2) {
for (int i = right, I >= left; i--) {
List.add (Matrix[buttom][i]);
}
buttom--;
}
if (dir = = 3) {
for (int i = buttom; I >= top; i--) {
List.add (Matrix[i][left]);
}
left++;
}
Dir = (dir + 1)% 4; Change direction!
}
return list;
}

public static void Main (string[] args) {
TODO auto-generated Method Stub
Int[][] arr = {{1, 2, 3, 4,5,6}, {7, 8, 9,10,11,12}, {12,13,14,15,16,17}};
Long long1 = System.currenttimemillis ();
System.out.print (Spiralorder (arr));
Long long2 = System.currenttimemillis ();
Long long3 = long2-long1;
SYSTEM.OUT.PRINTLN ("Time consuming" + Long3 + "milliseconds!") ");
}

}
Lesson: Why not use backtracking?

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