[LeetCode] Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:

[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

继续DFS
复制代码
 1 class Solution {
 2 private:
 3     int step[4][2];
 4     bool canUse[100][100];
 5 public:
 6     void dfs(int dep, vector<vector<int> > &matrix, int direct, int x, int y)
 7     {
 8         for(int i = 0; i < 4; i++)
 9         {
10             int j = (direct + i) % 4;
11             int tx = x + step[j][0];
12             int ty = y + step[j][1];
13             if (0 <= tx && tx < matrix.size() && 0 <= ty && ty < matrix[0].size() && canUse[tx][ty])
14             {
15                 canUse[tx][ty] = false;
16                 matrix[tx][ty] = dep;              
17                 dfs(dep + 1, matrix, j, tx, ty);               
18             }            
19         }
20     }
21     
22     vector<vector<int> > generateMatrix(int n) {
23         // Start typing your C/C++ solution below
24         // DO NOT write int main() function
25         step[0][0] = 0;
26         step[0][1] = 1;
27         step[1][0] = 1;
28         step[1][1] = 0;
29         step[2][0] = 0;
30         step[2][1] = -1;
31         step[3][0] = -1;
32         step[3][1] = 0;
33         vector<vector<int> > ret(n, vector<int>(n));
34         memset(canUse, true, sizeof(canUse));
35         dfs(1, ret, 0, 0, -1);
36         
37         return ret;        
38     }
39     
40 };
复制代码
posted @   chkkch  阅读(1535)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示