leetcode 54. 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 ],
[ 7, 8, 9 ]
]
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int>re;
if (matrix.empty() || matrix[0].empty())
return re;
if (matrix.size() == 1)
{
for (int i = 0; i < matrix[0].size(); i++)
re.push_back(matrix[0][i]);
return re;
}
if (matrix[0].size() == 1)
{
for (int i = 0; i < matrix.size(); i++)
re.push_back(matrix[i][0]);
return re;
}
int row = matrix.size();
int col = matrix[0].size();
int k = 0;
int off = 0;
while (true)
{
for (int i = off; i < col - off; i++)
{
re.push_back(matrix[off][i]); k++;
}
if (k == row*col )
return re;
for (int i = off + 1; i < row - off; i++)
{
re.push_back(matrix[i][col - 1 - off]); k++;
}
if (k == row*col)
return re;
for (int i = col - 2 - off; i >= off; i--)
{
re.push_back(matrix[row - 1 - off][i]); k++;
}
if (k == row*col)
return re;
for (int i = row - 2 - off; i >= off + 1; i--)
{
re.push_back(matrix[i][off]); k++;
}
if (k == row*col)
return re;
off++;
}
}
};
accepted
还没有评论,来说两句吧...