Vison's Blog
所有文章
文章总览
编辑器
Publications
About Me
Search
目录
#toc-container
下载Markdown文件
【3.16】LeetCode每日一题· 螺旋矩阵 II
2021年03月16日 11时03分
标签:
LeetCode
数组
## 题目描述 给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。 #### 示例1 [](https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg "示例1") 输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]] #### 示例2 输入:n = 1 输出:[[1]] #### 提示 1 <= n <= 20 #### 来源 > 来源:力扣(LeetCode) > 链接:[题目链接](https://leetcode-cn.com/problems/spiral-matrix-ii/ "题目链接") ## 解题思路 和昨天的[螺旋矩阵](http://www.vison307.com/36/ "螺旋矩阵")思路一样,模拟旋转即可。 ## 代码 class Solution { public: vector
> generateMatrix(int n) { vector
> res(n, vector
(n)); int cnt = 1, i = 0, j = 0, direct = 0; while(cnt <= n*n){ res[i][j] = cnt++; switch(direct){ case(0):{ if(j+1 < n && res[i][j+1] == 0){ j++; }else{ i++; direct++; } break; } case(1):{ if(i+1 < n && res[i+1][j] == 0){ i++; }else{ j--; direct++; } break; } case(2):{ if(j-1 >= 0 && res[i][j-1] == 0){ j--; }else{ i--; direct++; } break; } case(3):{ if(i-1 >= 0 && res[i-1][j] == 0){ i--; }else{ j++; direct = 0; } break; } } } return res; } }; ### 用时和内存 > 执行用时:0 ms,在所有 C\++提交中击败了100.00%的用户 > 内存消耗:6.4 MB,在所有 C\++提交中击败了64.20%的用户
所有评论
暂无评论
新增评论
评论
邮箱
邮箱仅作验证使用
图形验证码
邮箱验证码
发送验证码
发表评论
所有评论
暂无评论