Leetcode-59-螺旋矩阵
题目链接#
题目描述#
正整数 n ,生成一个 1 到 所有元素,且按顺时针顺序螺旋排列的正方形矩阵。
思路#
用(row, col) 表示要矩阵的坐标。
- 从(0, 0) 位置开始,依次按 右-下-左-上 的顺序插入元素
- 定义一个表示方向的数组
d[4][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};
- 下一个坐标的计算方式:(row+d[dIndex][0], col+d[dIndex][1])
- 当下个坐标位置不合法时, 更新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;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话