LeetCode Spiral Matrix II
来源:互联网 发布:sql 查询合并表语句 编辑:程序博客网 时间:2024/04/29 21:53
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]题意:将1到n^2的数依次填写进去。
思路:和上一道回旋的类似做法。
class Solution {public: vector<vector<int> > generateMatrix(int n) { vector<vector<int> > ans; for (int i = 0; i < n; i++) { vector<int> t = vector<int>(n, -1); ans.push_back(t); } int dx[4] = {0, 1, 0, -1}; int dy[4] = {1, 0, -1, 0}; int dir = 0, x = 0, y = 0; for (int i = 1; i <= n*n; i++) { ans[x][y] = i; if (x+dx[dir] == n || x+dx[dir] < 0 || y+dy[dir] == n || y+dy[dir] < 0 || ans[x+dx[dir]][y+dy[dir]] != -1) { dir = dir == 3 ? 0 : dir + 1; } x += dx[dir]; y += dy[dir]; } return ans; }};
0 0
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- Spiral Matrix II -- LeetCode
- MapReduce编程教训
- android ListView 学习(1)
- 溢出导致Sigabrt
- Android数据库升级
- 揭秘:乔布斯如何让才华横溢的工程师们效忠
- LeetCode Spiral Matrix II
- linux常用压缩解压命令(tar,zip)
- SDK没有可选包以及无法下载成功(uninstall),jdk、sdk、adb环境配置,官方文档镜像
- 什么是封装?
- Dijkstra算法实现
- MongoDB3.0介绍
- Makefile写法入门篇
- MySQL执行外部sql脚本文件命令是报错:unknown command '\'
- 【spring教程之六】spring注入内部类