【leetcode_medium】54. Spiral Matrix

leetcode_medium_array

problem

54. Spiral Matrix

solution #1: traverse from left to right, and then from down to up;

code

 

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty()) return res;
        int m = matrix.size();
        int n = matrix[0].size();
        int up = 0, down = m-1, left = 0, right = n-1;
        while(left<=right && up<=down ) // && res.size()<m*n
        {
            // why do check res.size in every for loop?
            for(int i=left; i<=right&& res.size()<m*n; i++)
            {
                res.push_back(matrix[up][i]);
            }
            up++;
            for(int i=up; i<=down&& res.size()<m*n; i++)
            {
                res.push_back(matrix[i][right]);
            }
            right--;
            for(int i=right; i>=left&& res.size()<m*n; i--)
            {
                res.push_back(matrix[down][i]);
            }
            down--;
            for(int i=down; i>=up&& res.size()<m*n; i--)
            {
                res.push_back(matrix[i][left]);
            }
            left++;
        }
        return res;
    }
};

  

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> res;
        if(matrix.empty()) return res;
        int m = matrix.size();
        int n = matrix[0].size();
        int up = 0, down = m-1, left = 0, right = n-1;
        while(left<=right && up<=down ) // && res.size()<m*n
        {
            // why do check res.size in every for loop?
            for(int i=left; i<=right&& res.size()<m*n; i++)
            {
                res.push_back(matrix[up][i]);
            }
            up++;
            for(int i=up; i<=down&& res.size()<m*n; i++)
            {
                res.push_back(matrix[i][right]);
            }
            right--;
            for(int i=right; i>=left&& res.size()<m*n; i--)
            {
                res.push_back(matrix[down][i]);
            }
            down--;
            for(int i=down; i>=up&& res.size()<m*n; i--)
            {
                res.push_back(matrix[i][left]);
            }
            left++;
        }
        return res;
    }
};

 

solution #2:

code 

 

solution #3:使用switch语句;

code:

 

参考

1. leetcode_54. Spiral Matrix;

posted on 2020-08-04 22:06  鹅要长大  阅读(90)  评论(0编辑  收藏  举报

导航