[LeetCode] Spiral Matrix II

The idea is just to generate the matrix in the spiral order. First the up-most row (u), then the right-most column (r), then the down-most row (d), and finally the left-most column (l). After generating a row or a column, update the corresponding variable to continue the generation.

The code is as follows.

复制代码
 1 class Solution {
 2 public:
 3     vector<vector<int> > generateMatrix(int n) { 
 4         vector<vector<int> > mat(n, vector<int>(n));
 5         int u = 0, d = n - 1, l = 0, r = n - 1, num = 1;
 6         while(true) {
 7             // up
 8             for(int col = l; col <= r; col++) mat[u][col] = num++;
 9             if(++u > d) break;
10             // right
11             for(int row = u; row <= d; row++) mat[row][r] = num++;
12             if(--r < l) break;
13             // down
14             for(int col = r; col >= l; col--) mat[d][col] = num++;
15             if(--d < u) break;
16             // left
17             for(int row = d; row >= u; row--) mat[row][l] = num++;
18             if(++l > r) break;
19         }
20         return mat;
21     }
22 };
复制代码

 

posted @   jianchao-li  阅读(162)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
点击右上角即可分享
微信分享提示