【LeetCode热题100】【矩阵】螺旋矩阵

题目链接:54. 螺旋矩阵 - 力扣(LeetCode)

先走外面的圈再走里面的圈,可以用递归来解决,对于要走的一个圈,由四个角决定,其实是三个数,(0,0),(0,n),(m,0),(m,n),每次先从左上角走到右上角,再走到右下角,再走到左下角,再走回来

对于后面两个的往回走要在m和n不等于起点的情况下,否则会重复最后

复制代码
class Solution {
public:
    vector<int> ans;
    vector<vector<int> > matrix;

    void go(int start, int row, int column) {
        if (start > row || start > column)
            return;
        for (int i = start; i <= column; ++i)
            ans.push_back(matrix[start][i]);
        for (int i = start + 1; i <= row; ++i)
            ans.push_back(matrix[i][column]);
        if (row != start)
            for (int i = column - 1; i >= start; --i)
                ans.push_back(matrix[row][i]);
        if (column != start)
            for (int i = row - 1; i > start; --i)
                ans.push_back(matrix[i][start]);
        go(start + 1, row - 1, column - 1);
    }

    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        this->matrix = move(matrix);
        go(0, this->matrix.size() - 1, this->matrix[0].size() - 1);
        return ans;
    }
};

不用递归也可以,改成迭代

复制代码
class Solution {
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
        vector<int> ans;
        int start = 0, row = matrix.size() - 1, column = matrix[0].size() - 1;
        while (true) {
            if (start > row || start > column)
                break;
            for (int i = start; i <= column; ++i)
                ans.push_back(matrix[start][i]);
            for (int i = start + 1; i <= row; ++i)
                ans.push_back(matrix[i][column]);
            if (row != start)
                for (int i = column - 1; i >= start; --i)
                    ans.push_back(matrix[row][i]);
            if (column != start)
                for (int i = row - 1; i > start; --i)
                    ans.push_back(matrix[i][start]);
            ++start;
            --row;
            --column;
        }
        return ans;
    }
};
相关推荐
.道阻且长.6 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
To_OC8 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
Forever Nore10 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
hansang_IR11 小时前
【题解】LC:倍增 / 区间并查集(Range Parallel Unionfind)
c++·算法·并查集
Tisfy12 小时前
LeetCode 3731.找出缺失的元素:哈希 / 排序
算法·leetcode·哈希算法·排序·哈希表
lucas_AI13 小时前
Q-CueGraph:你的多模态大模型会 zoom,但真的知道该看哪儿吗?
人工智能·算法
kaixin_啊啊13 小时前
test_机器学习算法学习
学习·算法·机器学习
liulilittle13 小时前
MOE路由:路由(logits: top-k/8)
c++·人工智能·算法·机器学习·llm
旖旎夜光13 小时前
LeetCode 11:盛最多水的容器(双指针问题) —— 题解
数据结构·c++·算法·leetcode·双指针