题解 | #牧场边界巡游#
牧场边界巡游
https://www.nowcoder.com/practice/bc7fe78f7bcc49a8bc0afdd7a55ca810
class Solution:
def spiralTravelCounterClockwise(self , matrix: List[List[int]]) -> List[int]:
# write code here
if not matrix:
return []
m, n = len(matrix), len(matrix[0])
res = []
def spiral(start_row, end_row, start_col, end_col):
if start_row > end_row or start_col > end_col:
return
# 遍历左侧的列
for i in range(start_row, end_row + 1):
res.append(matrix[i][start_col])
# 遍历下方的行
for j in range(start_col + 1, end_col+1):
res.append(matrix[end_row][j])
# 遍历右侧的列
if start_col < end_col:
for i in range(end_row-1, start_row-1, -1):
res.append(matrix[i][end_col])
# 遍历上方的行
if start_row < end_row:
for j in range(end_col-1,start_col,-1):
res.append(matrix[start_row][j])
# 递归处理内部的子矩阵
spiral(start_row + 1, end_row - 1, start_col + 1, end_col - 1)
spiral(0, m - 1, 0, n - 1)
return res
