螺旋矩阵 spiral-matrix
题目描述
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
例如,
给出以下矩阵:
[↵ [ 1, 2, 3 ],↵ [ 4, 5, 6 ],↵ [ 7, 8, 9 ]↵]
你应该返回[1,2,3,6,9,8,7,4,5]。
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].
解题思路
- 将螺旋矩阵看成一个个同心矩阵,从外往内一层一层地按照顺时针顺序遍历。
- 设定四个边界:left,right,top,bottom,初始分别为0,n - 1,0,m - 1
- 每一个同心矩阵的四个边界范围(从上面那条边开始)分别是left ~ right, top + 1 ~ bottom, right - 1 ~ left, bottom + 1~top - 1
- 每遍历完一个同心矩阵,left++, right- -, top- -, bottom++
- 注意,这题和螺旋矩阵ii题不同的地方是,遍历完上边界和右边界之后,在遍历下边界和左边界时,分别需要加上判断top < bottom、left < right,否则上下边界或左右边界出现重合,会重复读取。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> res;
int m = matrix.size();
if(0 == m) return res;
int n = matrix[0].size();
//四个边界
int left(0), right(n - 1), top(0), bottom(m - 1);
while(left <= right && top <= bottom) {
//上边界
for(int i = left; i <= right; i ++) {
res.push_back(matrix[top][i]);
}
//右边界
for(int i = top + 1; i <= bottom; i ++) {
res.push_back(matrix[i][right]);
}
//注意要加判断,如果top==bottm,则代表上下边界重合了,需要跳过
if(top < bottom) {
//下边界
for(int i = right - 1; i >= left; i --) {
res.push_back(matrix[bottom][i]);
}
}
//注意要加判断,如果left==right,则代表左右边界重合了,需要跳过
if(left < right) {
//左边界
for(int i = bottom - 1; i >= top + 1; i --) {
res.push_back(matrix[i][left]);
}
}
//进入下一个内层
left ++; right --; top ++; bottom --;
}
return res;
}
};