54. 螺旋矩阵

54. 螺旋矩阵

中等

给你一个 mn 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:

img

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

示例 2:

img

输入: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]

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

思路: 按照方向: 右->下->左->上 的思路模拟即可, 记录每一个走过的位置,总共要走m * n次

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        // 右 下 左 上
        vector<int> ans;
        int m = matrix.size();
        int n = matrix[0].size();
        vector<vector<int>> st(m, vector<int>(n, 0));
        int cnt = m * n;
        int i = 0, j = 0;
        ans.push_back(matrix[0][0]);
        st[0][0] = 1;
        cnt --;
        while(cnt) {
            while(j + 1 < n && !st[i][j + 1]) {
                j ++;
                ans.push_back(matrix[i][j]);
                st[i][j] = 1;
                cnt --;
            }

            while(i + 1 < m && !st[i + 1][j]) {
                i ++;
                ans.push_back(matrix[i][j]);
                st[i][j] = 1;
                cnt --;
            }

            while(j - 1 >= 0 && !st[i][j- 1]) {
                j --;
                ans.push_back(matrix[i][j]);
                st[i][j] = 1;
                cnt --;
            }


            while(i - 1 >= 0 && !st[i- 1][j]) {
                i --;
                ans.push_back(matrix[i][j]);
                st[i][j] = 1;
                cnt --;
            }

        }

        return ans;
    }
};
posted @ 2026-06-23 11:14  XYu1230  阅读(1)  评论(0)    收藏  举报