【Leetcode】【python】Spiral Matrix Spiral Matrix II 螺旋矩阵 螺旋矩阵 II

Spiral Matrix

题目大意

将一个矩阵中的内容螺旋输出。

注意点:

矩阵不一定是正方形
例子:

输入: matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
输出: [1, 2, 3, 6, 9, 8, 7, 4, 5]

解题思路

看代码就可以理解
注意:

while True:
然后里面自行判断结束

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution(object):
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix:
return []
up = 0
left = 0
down = len(matrix)-1
right = len(matrix[0])-1
direct = 0 # 0: go right 1: go down 2: go left 3: go up
res = []
while True:
if direct == 0:
for i in range(left, right+1):
res.append(matrix[up][i])
up += 1
if direct == 1:
for i in range(up, down+1):
res.append(matrix[i][right])
right -= 1
if direct == 2:
for i in range(right, left-1, -1):
res.append(matrix[down][i])
down -= 1
if direct == 3:
for i in range(down, up-1, -1):
res.append(matrix[i][left])
left += 1
if up > down or left > right:
return res
direct = (direct+1) % 4

Spiral Matrix II

题目大意

将一个正方形矩阵螺旋着填满递增的数字。

解题思路

螺旋填满数字

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
if n == 0:
return []
matrix = [[0 for i in range(n)] for j in range(n)] # 创建矩阵
up = 0
down = len(matrix)-1
left = 0
right = len(matrix[0])-1
direct = 0
count = 0
while True:
if direct == 0:
for i in range(left, right+1):
count += 1; matrix[up][i] = count
up += 1
if direct == 1:
for i in range(up, down+1):
count += 1; matrix[i][right] = count
right -= 1
if direct == 2:
for i in range(right, left-1, -1):
count += 1; matrix[down][i] = count
down -= 1
if direct == 3:
for i in range(down, up-1, -1):
count += 1; matrix[i][left] = count
left += 1
if count == n*n:
return matrix
direct = (direct+1) % 4

总结