题目描述:
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路:
用四个遍历标记四个方向
上:top—1
下:bootom—2
左:left—3
右:right—4
总共有四个步骤,3—4,1—2,4—3,2—1,每一次都对边界值进行修改。
代码:
内容中有解释
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.size() == 0 || matrix[0].size() == 0) return res;
//四个方向
int top = 0;
int bottom = matrix.size() - 1;
int left = 0;
int right = matrix[0].size() - 1;
while (true) {
for (int i = left; i <= right; i++)
res.push_back(matrix[top][i]);//从左到右,依次存入res
top++;
if (left > right || top > bottom) //界限
break;
for (int i = top; i <= bottom; i++) //从上到下,依次存入res
res.push_back(matrix[i][right]);
right--;
if (left > right || top > bottom)
break;
for (int i = right; i >= left; i--)
res.push_back(matrix[bottom][i]);
bottom--;
if (left > right || top > bottom)
break;
for (int i = bottom; i >= top; i--)
res.push_back(matrix[i][left]);
left++;
if (left > right || top > bottom)
break;
}
return res;
}
};
结果显示: