title : Spiral Matrix
Difficulty : Medium
topic content :
Given a matrix of m x n elements (m rows, n columns), return all elements of the Matri X in Spiral Order.
translation :
Given a matrix of M x n elements (m rows, n columns), all elements of the matrix are returned in a clockwise spiral order.
Example 1:
input:[[1, 2, 3], [4, 5, 6], [7, 8, 9]]output: [1,2,3,6,9,8,7,4,5]
Example 2:
input:[ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]]output: [1,2,3,4,8,12,11,10,9,5,6,7]
my idea : Because every lap is composed of four sides, so write a while dead loop, inside there are four for loops, each for the end of the corresponding indicator will be reduced, at the same time to determine whether exceeding the standard, the exit.
eg
while (true) {
Sideways for add
Top + +
Whether top is less than bottom is the break
。。。
}
My Code :
1 PublicList<integer> Spiralorder (int[] matrix) {2list<integer> res =NewArraylist<integer>();3 if(Matrix.length = = 0 | | matrix[0].length = = 0)returnRes;4 5 inttop = 0;6 intBottom = Matrix.length-1;7 intleft = 0;8 intright = Matrix[0].length-1;9 Ten while(true){ One for(inti = left; I <= right; i++) Res.add (Matrix[top][i]); Atop++; - if(Left > Right | | top > Bottom) Break; - the for(inti = top; I <= bottom; i++) Res.add (Matrix[i][right]); -right--; - if(Left > Right | | top > Bottom) Break; - + for(inti = right; I >= left; i--) Res.add (Matrix[bottom][i]); -bottom--; + if(Left > Right | | top > Bottom) Break; A at for(inti = bottom; I >= top; i--) Res.add (Matrix[i][left]); -left++; - if(Left > Right | | top > Bottom) Break; - } - - returnRes; in}
my complexity : O (N * M) rows multiplied by columns
problems in the encoding process :
1, did not notice that when the input is an empty array, right and bottom will be negative, so we have to add a sentence empty.
Answer code :
The same as me.
Leetcode [54] (Java): Spiral Matrix