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