题目描述
给你一个 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
解题思路
这道题不涉及复杂难懂的算法,是一道模拟题。我们只需要去模拟螺旋的过程就可以得出答案。
为了模拟螺旋的过程,我们需要标记二维表的四个角的位置:左上(top,left),左下(bottom,left),右上(top,right),右下(bottom,right)。容易看出的是,我们只需要标记上(top)下(bottom)左(left)右(right)四个边界就可以了。
然后就是螺旋的过程,每一次都按螺旋的顺序遍历最外层的元素:
-
从左到右遍历上侧元素,依次为 (top,left) 到(top,right),然后top++;
-
从上到下遍历右侧元素,依次为 (top,right) 到 (bottom,right),然后right--;
-
从右到左遍历下侧元素,依次为(bottom,right) 到 (bottom,left),然后bottom--;
-
从下到上遍历左侧元素,依次为(bottom,left) 到(top,left),然后left++。
在遍历每一层的时候都需要符合条件
。top<=bottom && left<=right
`,并且,在进行以上4个步骤的时候也需要符合条件
`top<=bottom && left<=right
最终,我们可以得出完整代码。
示例代码
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
vector<int>res;
if(matrix.size()==0||matrix[0].size()==0)
{
return {};
}
int top=0;
int bottom=matrix.size()-1;
int left=0;
int right=matrix[0].size()-1;
while(top<=bottom && left<=right)
{
if(top<=bottom && left<=right)
{
for(int i=left;i<=right;++i)
{
res.push_back(matrix[top][i]);
}
}
top++;
if(top<=bottom && left<=right)
{
for(int i=top;i<=bottom;++i)
{
res.push_back(matrix[i][right]);
}
}
right--;
if(top<=bottom && left<=right)
{
for(int i=right;i>=left;--i)
{
res.push_back(matrix[bottom][i]);
}
}
bottom--;
if(top<=bottom && left<=right)
{
for(int i=bottom;i>=top;--i)
{
res.push_back(matrix[i][left]);
}
}
left++;
}
return res;
}
文章评论