输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 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]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
顺时针打印 那么就顺时针遍历该二维数组,定义left right top bottom四个边界值,
从左到右遍历完成后,top++
再从上到下遍历 遍历完成后,right–,
再从右到左遍历 遍历完成后 bottom–,
再从下到上遍历 遍历完成后 left–,
完成以上四个操作的 每次都需要判断 lefttop。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size()==0)return {};
vector<int>res;
int top=0;
int left=0;
int right=matrix[0].size()-1;
int bottom=matrix.size()-1;
while(true)
{
for(int j=left;j<=right;j++)//左到右
{
res.push_back(matrix[top][j]);
}
top++;//完成后 下次从左到右 应该是下一行
if(top>bottom)break;//边界判断
for(int i=top;i<=bottom;i++)//从上到下
{
res.push_back(matrix[i][right]);
}
right--;//右一列完成后 右边界左移
if(right<left)break;
for(int k=right;k>=left;k--)//再从右到左
{
res.push_back(matrix[bottom][k]);
}
bottom--;//下一行完成后 下边界上移
if(bottom<top)break;
for(int m=bottom;m>=top;m--)//再从下到上
{
res.push_back(matrix[m][left]);
}
left++;//左一列完成后,左边界右移
if(left>right)break;
}
return res;
}
};