力扣 54. 螺旋矩阵 模拟

https://leetcode-cn.com/problems/spiral-matrix/在这里插入图片描述
思路:螺旋遍历,模拟这个过程即可。想象成一个四边形在逐渐缩小……

class Solution {
    
    
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
    
    
        int top=0,down=matrix.size()-1,left=0,right=matrix[0].size()-1,times=0;
        vector<int> ans;
        while(top<=down&&left<=right)
        {
    
    
            switch(times)
            {
    
    
                case 0:
                    for(int i=left;i<=right;i++)
                        ans.push_back(matrix[top][i]);
                    ++top;
                    break;
                case 1:
                    for(int i=top;i<=down;i++)
                        ans.push_back(matrix[i][right]);
                    --right;
                    break;
                case 2:
                    for(int i=right;i>=left;i--)
                        ans.push_back(matrix[down][i]);
                    --down;
                    break;
                case 3:
                    for(int i=down;i>=top;i--)
                        ans.push_back(matrix[i][left]);
                    ++left;
                    break;
            }
            times=(times+1)%4;
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/114835269