[Leetcode]Spiral Matrix II
2015-01-13 22:04
337 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
You should return the following matrix:
跟Spiral Matrix类似,让你把1~n2这些数按螺旋顺序放入矩阵中~做法也是类似的,使用0,1,2,3四个值表示上下左右四个方向以便切换,
用top, bottom, left, right四个变量记录四个边界,复杂度是O(n^2)
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
跟Spiral Matrix类似,让你把1~n2这些数按螺旋顺序放入矩阵中~做法也是类似的,使用0,1,2,3四个值表示上下左右四个方向以便切换,
用top, bottom, left, right四个变量记录四个边界,复杂度是O(n^2)
class Solution: # @return a list of lists of integer def generateMatrix(self, n): if n <= 0: return [] dir, top, bottom, left, right = 0, 0, n - 1, 0, n - 1 res = [[0 for i in xrange(n)] for j in xrange(n)]; count = 1 while count <= n * n: if dir == 0: for i in xrange(left, right + 1): res[top][i] = count count += 1 top += 1 elif dir == 1: for i in xrange(top, bottom + 1): res[i][right] = count count += 1 right -= 1 elif dir == 2: for i in reversed(xrange(left, right + 1)): res[bottom][i] = count count += 1 bottom -= 1 else: for i in reversed(xrange(top, bottom + 1)): res[i][left] = count count += 1 left += 1 dir = (dir + 1) % 4 return res
相关文章推荐
- leetcode做题总结,题目Spiral Matrix I/II 2012/03/24
- LeetCode 59. Spiral Matrix II
- leetcode第一刷_Spiral Matrix II
- Leetcode:Spiral Matrix与Spiral Matrix II
- Spiral Matrix II leetcode java
- leetcode Spiral Matrix II
- leetcode 59. Spiral Matrix II
- [leetcode]Spiral Matrix II
- [LeetCode] Spiral Matrix II
- 牛客:剑指offer:顺时针打印矩阵 (Java)(同leetcode的spiral matrix i 和ii)
- LeetCode | Spiral Matrix II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- LeetCode : Spiral Matrix II
- LeetCode 54/59. Spiral Matrix i, ii
- Leetcode: Spiral Matrix II
- 62 leetcode - Spiral Matrix II
- [C++]LeetCode: 111 Spiral Matrix II (螺旋写入矩阵)
- Java for LeetCode 059 Spiral Matrix II
- LeetCode 059 Spiral Matrix II
- 【leetcode】第59题 Spiral Matrix II 题目+解析+代码