一.题目要求
给你一个 m 行 n 列的矩阵 matrix ,请按照顺时针螺旋顺序 ,返回矩阵中的所有元素。
二.题目难度
中等
三.输入样例
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
四.解题思路
找到四个方向坐标变化的规律遍历即可
五.代码实现
优化后
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> sup;
int width = matrix.size();
int length = matrix[0].size();
int left = 0;
int right = length - 1;
int top = 0;
int bottom = width - 1;
while (left <= right && top <= bottom)
{
for (int i = left; i <= right; i++)
{
sup.push_back(matrix[top][i]);
}
top++;
for (int i = top; i <= bottom; i++)
{
sup.push_back(matrix[i][right]);
}
right--;
if (top <= bottom)
{
for (int i = right; i >= left; i--)
{
sup.push_back(matrix[bottom][i]);
}
bottom--;
}
if (left <= right)
{
for (int i = bottom; i >= top; i--)
{
sup.push_back(matrix[i][left]);
}
left++;
}
}
return sup;
}
};
优化前
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int wid = matrix.size();
int len = matrix[0].size();
int crtlen = len;
int crtwid = wid;
vector<int> ans;
bool lefttoright = true;
bool toptobottom = true;
int lenindex = 0, widindex = 0, i;
while (crtlen && crtwid)
{
if (lefttoright)
{
for (i = 0; i < crtlen; i++)
{
ans.push_back(matrix[lenindex][widindex++]);
}
lenindex++; widindex--;
lefttoright = !lefttoright;
crtwid--;
}
else
{
for (i = 0; i < crtlen; i++)
{
ans.push_back(matrix[lenindex][widindex--]);
}
lenindex--; widindex++;
lefttoright = !lefttoright;
crtwid--;
}
if (toptobottom)
{
for (i = 0; i < crtwid; i++)
{
ans.push_back(matrix[lenindex++][widindex]);
}
widindex--; lenindex--;
toptobottom = !toptobottom;
crtlen--;
}
else
{
for (i = 0; i < crtwid; i++)
{
ans.push_back(matrix[lenindex--][widindex]);
}
widindex++;lenindex++;
toptobottom = !toptobottom;
crtlen--;
}
}
return ans;
}
};
六.题目总结
注意溢出判断