Leetcode 59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
想法是先生成一个矩阵之后一个一个往里按顺序往里面填数字,代码如下:
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 1:
return[[1]]
output = [[0]*n for _ in range(n)]
cur = 1
total = n * n
left = 0
right = n
top = 0
bottom = n
while cur <= total:
for i in range(left, right):
output[top][i] = cur
cur += 1
top += 1
for i in range(top, bottom):
output[i][right-1] = cur
cur += 1
right -= 1
for i in range(right-1, left-1, -1):
output[bottom-1][i] = cur
cur += 1
bottom -= 1
for i in range(bottom-1, top-1, -1):
output[i][left] = cur
cur += 1
left += 1
return output
beat 54%+
需要注意
我发现python在初始化数组的时候,如果使用
output = [[0] * n] * n
会导致得到的
[[0,0,0],
[0,0,0],
[0,0,0]]
其实里面的三个数组共享一个地址会一起变化,出了很多bug,可能是python本身变量就是指针的缘故还特别节约资源,之后会看看python核心再重新补一下基础。
Discuss 中的解法
1. 用一个turple 控制方向:
class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
matrix = [[0]*n for _ in range(n)]
directions = ((0, 1), (1, 0), (0, -1), (-1, 0))
d = 0
y, x = 0, 0
for i in range(1, n*n+1):
matrix[y][x] = i
dy, dx = directions[d % 4]
if -1 < y+dy < n and -1 < x+dx < n and matrix[y+dy][x+dx] == 0:
y, x = y+dy, x+dx
else:
d += 1
dy, dx = directions[d % 4]
y, x = y+dy, x+dx
return matrix
2.各种神奇巧妙:
https://leetcode.com/problems/spiral-matrix-ii/discuss/22282/4-9-lines-Python-solutions