54. 螺旋矩阵(剑指 Offer 29. 顺时针打印矩阵)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
ans = []
count = 0
m, n = len(matrix), len(matrix[0])
length = m * n
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
x = y = Dir = 0
while count < length:
ans.append(matrix[x][y])
matrix[x][y] = 'a'
dx, dy = directions[Dir]
if x + dx >= m or y + dy >= n or x + dx < 0 or y + dy < 0 or matrix[x + dx][y + dy] == 'a':
Dir = Dir + 1 if Dir < 3 else 0
dx, dy = directions[Dir]
x += dx
y += dy
count += 1
return ans
首先考虑到,元素前进的方向只有四个,对应方向的 x 与 y 如何变化是确定的。所以用一个direction 数组保存四个方向 [(0, 1), (1, 0), (0, -1), (-1, 0)]。另外要注意防止跑出界,每次准备跑出界时就转向。对于已经取过数的格子,把它置 ‘a’ 即可,下一格为 ‘a’ 就转向。
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
matrix = [[0] * n for _ in range(n)]
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
x = y = Dir = 0
for i in range(1, n**2 + 1):
matrix[x][y] = i
dx, dy = directions[Dir]
if x + dx >= n or y + dy >= n or x + dx < 0 or y + dy < 0 or matrix[x + dx][y + dy] != 0:
Dir = Dir + 1 if Dir < 3 else 0
dx, dy = directions[Dir]
x += dx
y += dy
return matrix
与上一题类似,区别在于本题不是给定矩阵求遍历序列,而是给定一个数字 n 然后返回一个 n**2 大小的矩阵。
class Solution:
def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
ans= []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
Left, Right, Upper, Bottom = cStart - 1, cStart + 1, rStart - 1, rStart + 1 # 四个方向的边界
x, y, num, Dir = rStart, cStart, 1, 0 # (x, y)为当前节点,num为当前查找的数字,Dir为当前的方向
while num <= rows * cols:
if x >= 0 and x < rows and y >= 0 and y < cols: # (x, y)在矩阵中
ans.append([x, y])
num += 1
if Dir == 0 and y == Right: # 向右到右边界
Dir += 1 # 调转方向向下
Right += 1 # 右边界右移
elif Dir == 1 and x == Bottom: # 向下到底边界
Dir += 1
Bottom += 1 # 底边界下移
elif Dir == 2 and y == Left: # 向左到左边界
Dir += 1
Left -= 1 # 左边界左移
elif Dir == 3 and x == Upper: # 向上到上边界
Dir = 0
Upper -= 1 # 上边界上移
dx, dy = directions[Dir]
x += dx
y += dy
return ans
本题可以看作是给定一个起始点,其上下左右为边界,然后开始顺时针遍历,如果元素正好在矩阵中,那就符合条件,加入到遍历序列 ans 中。如果遇到边界就把边界向外扩展,然后顺时针转向,再遍历下一个,直到把矩阵所有元素都遍历过为止。