LeetCode Hot 100系列:螺旋矩阵(Q54)

1.题目信息

54.螺旋矩阵icon-default.png?t=O83Ahttps://leetcode.cn/problems/spiral-matrix/?envType=study-plan-v2&envId=top-100-liked

2.解题思路

       模拟

        直观的方法是模拟,模拟螺旋矩阵的过程,一开始想观察下标的变化规律写循环,发现不可行,因为每一圈的次数都在减一,所以需要开一个方向指针二维数组,代表右下上左四个方向。

        模拟时有几个注意点,一是要存一个矩阵大小的标记矩阵,标记这个点是否走过,就像dfs那样。二是创建nextrow和nextcol两个变量用于每次移动测试,方便更新。三是判断移动方向的取余操作,这样可以方便的使用方向数组。

class Solution {
private:
    static constexpr int directions[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
public:
    vector spiralOrder(vector>& matrix) {
        int rows = matrix.size(),cols = matrix[0].size();
        if(rows == 0 || cols ==0){
            return {};
        }
        vector> visited(rows,vector(cols));
        int total = rows * cols;
        vector res(total);

        int row = 0,col=0;
        int dirindex=0;
        for(int i=0;i= rows || nextcol<0 || nextcol>=cols || visited[nextrow][nextcol]){
                dirindex = (dirindex+1)%4;
            }
            row += directions[dirindex][0];
            col += directions[dirindex][1];
        }
        return res;
    }
};

        缩小矩阵边界

四个指针转圈圈
  • 从左到右,顶部一层遍历完往下移一位,top++;
  • 从上到下,遍历完右侧往左移一位,right--;
  • 从右到左,判断top <= bottom,即是否上下都走完了。遍历完底部上移,bottom--;
  • 从下到上,判断left <= right,遍历完左侧右移,left++;
class Solution {
public:
    vector spiralOrder(vector>& matrix) {
        int m = matrix.size(),n = matrix[0].size();
        if(m == 0 || n ==0){
            return {};
        }
        vector res;
        int top = 0,bottom = m-1;
        int left = 0,right = n-1;
        while(left<=right && top<=bottom){
            //从左往右
            for(int i=left;i<=right;i++){
                res.push_back(matrix[top][i]);
            }
            top++;
            //从上到下
            for(int i=top;i<=bottom;i++){
                res.push_back(matrix[i][right]);
            }
            right--;
            //从右到左
            if(top<=bottom){
                for(int i=right;i>=left;i--){
                    res.push_back(matrix[bottom][i]);
                }
            }
            bottom--;
            //从下到上
            if(left<=right){
                for(int i=bottom;i>=top;i--){
                    res.push_back(matrix[i][left]);
                }
            }
            left++;
        }
        return res;
    }
};

        在进行从右到左的遍历之前,先判断 top <= bottom。这是因为只有当还有未遍历的垂直行时(即 top 还小于等于 bottom),才需要进行从右到左沿着底部行的遍历。如果 top 已经大于 bottom,说明垂直方向的元素已经全部遍历完了,此时就不需要再执行这个从右到左的遍历操作了,否则会导致越界访问矩阵元素的错误。

你可能感兴趣的:(LeetCode,Hot,100,leetcode,矩阵,算法)