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].
思路:蛇形矩阵。设立四个方向的边界,然后模拟一遍即可。
// 3 ms
class Solution {
public:
/*蛇形矩阵
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
=> [1,2,3,6,9,8,7,4,5]
*/
vector<int> spiralOrder(vector<vector<int> >& matrix)
{
vector<int> res;
int x = 0, y = 0, tot = 0; //tot用于计数,作为停止条件
int m = matrix.size();
if(m == 0) //错误输入数据,特殊处理
return res;
int n = matrix[0].size();
int up = 0, down = m-1, left = 0, right = n-1;
if(n==0) //错误输入数据,特殊处理
return res;
//开始遍历
while(tot < m*n)
{
while(x==up && tot < m*n) //最上面一行
{
res.push_back(matrix[x][y]);
tot++;
if(y == right)
x++;
else
y++;
}
up += 1;
while(y==right && tot < m*n)
{
res.push_back(matrix[x][y]);
tot++;
if(x == down)
y--;
else
x++;
}
right -= 1;
while(x==down && tot < m*n)
{
res.push_back(matrix[x][y]);
tot++;
if(y == left)
x--;
else
y--;
}
down -= 1;
while(y==left && tot < m*n)
{
res.push_back(matrix[x][y]);
tot++;
if(x == up)
y++;
else
x--;
}
left += 1;
}
//cout<<up<<down<<left<<right;
return res;
}
};
在solution中看到更简洁的代码(思路是一样的),据称 0ms,交上去呵呵了,也是3 ms
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> spiral(m * n);
int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
while (true) {
// up
for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
if (++u > d) break;
// right
for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
if (--r < l) break;
// down
for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
if (--d < u) break;
// left
for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
if (++l > r) break;
}
return spiral;
}
};