首页 > 数据库 >[Oracle] LeetCode 54 Spiral Matrix 模拟

[Oracle] LeetCode 54 Spiral Matrix 模拟

时间:2022-10-02 21:45:32浏览次数:79  
标签:matrix int 54 Spiral down ans left dir Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Solution

点击查看代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int r = matrix.size(), c = matrix[0].size();
        vector<int> ans;
        int top = 0, down = r-1, left = 0, right = c-1;
        int dir=0;
        while(top<=down && left<=right){
            if(dir==0){
                for(int i=left;i<=right;i++)
                    ans.push_back(matrix[top][i]);
                dir=1;
                top++;
            }
            else if(dir==1){
                for(int i=top;i<=down;i++)
                    ans.push_back(matrix[i][right]);
                dir=2;
                right--;
            }
            else if(dir==2){
                for(int i=right;i>=left;i--)
                    ans.push_back(matrix[down][i]);
                dir=3;
                down--;
            }
            else if(dir==3){
                for(int i=down;i>=top;i--)
                    ans.push_back(matrix[i][left]);
                dir=0;
                left++;
            }
        }
        return ans;
    }
};

标签:matrix,int,54,Spiral,down,ans,left,dir,Matrix
From: https://www.cnblogs.com/xinyu04/p/16749533.html

相关文章