Title Link: Spiral Matrix
Given a matrix of M x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ],
You should return [1,2,3,6,9,8,7,4,5].
The requirement of this problem is to give the matrix of the m*n, returning all elements in a spiral order (clockwise).
A simple array manipulation problem is simply to iterate through the array by row or column in the right, bottom, left, and upper order. However, you need to be aware of the boundary problem, assuming the current position in [X, Y]:
- When the right traversal, because X does not change, y each add 1, therefore requires Y to be less than n-x;
- When traversing down, because Y is constant, X is added 1 at a time, so X is required to be less than M (n-y-1).
- When traversing to the left, Y minus 1 per time because X does not change, so y is required to be less than m-x-1;
- When traversing up, X is reduced by 1 for each time because Y is unchanged, so it is required that x is less than y+1.
Time complexity: O (MN)
Space complexity: O (MN)
1 class Solution2 {3 Public:4 Vector<int> Spiralorder(Vector<Vector<int> > &Matrix)5 {6 Vector<int> VI;7 8 if(Matrix.size() == 0)9 return VI;Ten One int m = Matrix.size(), N = Matrix[0].size(); A int x = 0, y = 0, mn = m * N - 1; - VI.push_back(Matrix[x][y]); - the while(mn > 0) - { - while(y + 1 < N - x && mn -- > 0) - VI.push_back(Matrix[x][++ y]); + - while(x + 1 < m - (N - y - 1) && mn -- > 0) + VI.push_back(Matrix[++ x][y]); A at while(y - 1 >= m - x - 1 && mn -- > 0) - VI.push_back(Matrix[x][-- y]); - - while(x - 1 >= y + 1 && mn -- > 0) - VI.push_back(Matrix[-- x][y]); - } in - return VI; to } + };
Reprint please indicate source: Leetcode---54. Spiral Matrix
Leetcode---54. Spiral Matrix