LeetCode 59.Spiral Matrix || (Medium)
来源:互联网 发布:淘宝店铺起名字大全 编辑:程序博客网 时间:2024/06/05 22:40
原题地址:https://leetcode.com/problems/spiral-matrix-ii/description/
题目描述:
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 ]
]
题解:
给出一个整型n,创建一个大小按顺时针增长的行列均为n的矩阵。解法和上一题相同,在已知n的情况下只需创建一个n*n的空矩阵,再按打印的方法将数字填进去就行。
代码:
class Solution {public: vector<vector<int>> generateMatrix(int n) { if (n == 0) return vector<vector<int>>(); int x = 0, y = 0; int cntNumber = n*n; int count = 0, queryNum = 0; vector<vector<int>> output(n, vector<int>(n)); while (true) { for (; y < n - queryNum; y++) { output[x][y] = ++count; } y--; x++; if (count == cntNumber) break; for (; x < n - queryNum; x++) { output[x][y] = ++count; } x--; y--; if (count == cntNumber) break; for (; y >= queryNum; y--) { output[x][y] = ++count; } y++; x--; if (count == cntNumber) break; for (; x > queryNum; x--) { output[x][y] = ++count; } x++; y++; if (count == cntNumber) break; queryNum++; } return output; }};
21 / 21 test cases passed.
Status: Accepted
Runtime: 3 ms
阅读全文
0 0
- LeetCode 59.Spiral Matrix || (Medium)
- Leetcode 59. Spiral Matrix II (Medium) (cpp)
- Leetcode 59. Spiral Matrix II (Medium) (java)
- [Leetcode 54, Medium] Spiral Matrix
- 【LeetCode】(54)Spiral Matrix(Medium)
- LeetCode 54.Spiral Matrix (Medium)
- 【LeetCode】(59)Spiral Matrix II(Medium)
- LeetCode-59-Spiral Matrix II(Array)-Medium
- Leetcode 54. Spiral Matrix (Medium) (cpp)
- Leetcode 54. Spiral Matrix (Medium) (java)
- 【Leet Code】59. Spiral Matrix II---Medium
- Spiral Matrix(medium)
- LeetCode-54-Spiral Matrix(矩阵/模拟/递归)-Medium
- [LeetCode]59.Spiral Matrix II
- LeetCode --- 59. Spiral Matrix II
- [Leetcode] 59. Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode 59. Spiral Matrix II
- 修改注册表屏蔽或替换键盘上的某个按键
- 中介者模式
- Linux系统下编译sqlite有关.c文件,显示fatal error: sqlite3.h: No such file or directory错误
- java集合一
- Android JNI接口混淆方案
- LeetCode 59.Spiral Matrix || (Medium)
- eclipse的Ctrl+Alt+方向键在英特尔显示器上会切换屏幕方向
- 获取ip地址的方法
- Python 2.6 升级到3.6
- CSS笔记:简析margin,padding,border
- grafana 页面报错被重定向次数过多,后台报 Failed to start session%!(EXTRA *os.PathError=open /var/lib/grafana/session
- 基数排序
- Collection容器初探之LinkedList
- 使用nc获取cmdshell