LeetCode54,59,885题 螺旋矩阵I,II,II(蛇形矩阵)


这类题,都是纯模拟题,定义一个方向数组,然后一个变量d表示当前在哪个方向上

LeetCode 54.螺旋矩阵 I

在这里插入图片描述

class Solution {
public: 
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (!matrix.size() || !matrix[0].size()) return {};
        int m = matrix.size(), n = matrix[0].size();
        vector<int> res;
        vector<vector<bool>> st(m, vector<bool>(n, false));
        int x = 0, y = 0, d = 0;
        int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};

        for (int i = 0; i < m * n; i ++) {
            res.push_back(matrix[x][y]);
            st[x][y] = true;

            // 看下一个点是否可行
            int a = x + dx[d], b = y + dy[d];
            if (a < 0 || a >= m || b < 0 || b >= n || st[a][b]) d = (d + 1) % 4;
            
            x += dx[d];
            y += dy[d];
        }
        return res;
    }
};

LeetCode 59.螺旋矩阵 II

在这里插入图片描述

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
        int x = 0, y = 0, d = 0;

        for (int i = 1; i <= n * n; i ++) {
            res[x][y] = i;

            // 下一个点是否可行
            int a = x + dx[d], b = y + dy[d];
            if (a < 0 || a >= n || b < 0 || b >= n || !res[a][b]) {
                d = (d + 1) % 4;
            }

            x += dx[d];
            y += dy[d]; 
        }
        
        return res;
    }
};

LeetCode 885.螺旋矩阵 III

在这里插入图片描述
在这里插入图片描述

class Solution {
public:
    vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
        int tot = R * C;
        int cnt = 1;
        int x = r0, y = c0, d = 0;
        int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
        vector<vector<int>> res;
        if (x >= 0 && x < R && y >= 0 && y < C) {
            res.push_back({x, y});
            tot --;
        }
        // 步长:1 1 2 2 3 3...
        while(tot) {
            int len = (cnt - 1) / 2 + 1;
            for (int i = 1; i <= len; i ++) {
                x += dx[d];
                y += dy[d];
                // 若在范围内,就加到res
                if (x >= 0 && x < R && y >= 0 && y < C) {
                    res.push_back({x, y});
                    tot --;
                }
            }
            // 走完步长后,改变方向
            d = (d + 1) % 4;
            cnt ++;
        }

        return res;
    }
};
发布了182 篇原创文章 · 获赞 71 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104105658