螺旋矩阵

给你一个 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]

思路:设置好边界条件,要注意细节

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int num =n*m;
        int i=0,j=0;
        int left = 0,right = n-1,top = 0,buttom = m-1;
        int direction = 1;
        vector<int> res;
        while(num--){
            if(direction == 1){
                if(j<right){
                    res.emplace_back(matrix[i][j]);
                    j++;
                }else{
                    res.emplace_back(matrix[i][j]);
                    right--;
                    direction =2;
                    i++;
                }
            }
            else if(direction == 2){
                if(i<buttom){
                    res.emplace_back(matrix[i][j]);
                    i++;
                }else{
                    res.emplace_back(matrix[i][j]);
                    buttom--;
                    direction =3;
                    j--;
                }
            }         
            else if(direction == 3){
                if(j>left){
                    res.emplace_back(matrix[i][j]);
                    j--;
                }else{
                    res.emplace_back(matrix[i][j]);
                    left++;
                    direction =4;
                    i--;
                }
            }
            else{
                if(i>top+1){
                    res.emplace_back(matrix[i][j]);
                    i--;
                }else{
                    res.emplace_back(matrix[i][j]);
                    top++;
                    direction = 1;
                    j++;
                }
            }
        }
        return res;
    }
};

 

posted on 2024-12-20 21:41  _月生  阅读(10)  评论(0)    收藏  举报