Leetcode-59-螺旋矩阵

题目链接#


题目描述#

正整数 n ,生成一个 1 到 n2 所有元素,且按顺时针顺序螺旋排列的正方形矩阵。

思路#

(row, col) 表示要矩阵的坐标。

  1. (0, 0) 位置开始,依次按 右-下-左-上 的顺序插入元素
  2. 定义一个表示方向的数组 d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
  3. 下一个坐标的计算方式:(row+d[dIndex][0], col+d[dIndex][1])
  4. 当下个坐标位置不合法时, 更新dIndex,开始下个方向的插入。

C++代码#

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> m(n, vector<int>(n));

        int cnt = n*n;

        // 设置方向 右下左上
        int d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
        int dIndex = 0, tc, tr;
        int row = 0, col = 0;

        for (int i = 1; i <= cnt; i++) {
            m[row][col] = i;

            // 判断当前方向下一个位置是否合法
            tr = row+d[dIndex][0];
            tc = col+d[dIndex][1];
            if (tr==n || tc==n || tc==-1 || m[tr][tc])  // 若不合理 更新方向
                dIndex = (dIndex+1) % 4;

            // 下一个位置
            row = row+d[dIndex][0];
            col = col+d[dIndex][1];
        }

        return m;
    }
};
posted @   ARUI丶  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示
主题色彩