LeetCode:Spiral Matrix
Spiral Matrix
Total Accepted: 53006
Total Submissions: 240172
Difficulty: Medium
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:
You should return
Subscribe to see which companies asked this question
Hide Tags
Array
Hide Similar Problems
(M) Spiral Matrix II
code:
Total Accepted: 53006
Total Submissions: 240172
Difficulty: Medium
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 ],
[ 7, 8, 9 ]
]
You should return
[1,2,3,6,9,8,7,4,5]
. Subscribe to see which companies asked this question
Hide Tags
Array
Hide Similar Problems
(M) Spiral Matrix II
code:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ret;
if(matrix.empty() || 0==matrix.size()) return ret;
int m = matrix.size();
int n = matrix[0].size();
int rowStart = 0, rowEnd = m-1;
int colStart = 0, colEnd = n-1;
while(rowStart <= rowEnd && colStart <= colEnd) {
for(int i=colStart;i<=colEnd;i++) // left -> right
ret.push_back(matrix[rowStart][i]);
rowStart++;
for(int i=rowStart;i<=rowEnd;i++) // up -> down
ret.push_back(matrix[i][colEnd]);
colEnd--;
if(rowStart<=rowEnd) {
for(int i=colEnd;i>=colStart;i--) // right -> left
ret.push_back(matrix[rowEnd][i]);
rowEnd--;
}
if(colStart<=colEnd) {
for(int i=rowEnd;i>=rowStart;i--) // down -> up
ret.push_back(matrix[i][colStart]);
colStart++;
}
}
return ret;
}
};