力扣1091 https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/
python3
启发:过去一两个月的笔试过程中,最最怕遇到的就是输入为矩阵的题型,一直不知道该怎么遍历某以位置的相邻8个节点。今天在leetcode刷题终于遇到了,才发现还是有一个比较正规的遍历方法。设置两个数组x和y,分别代表当前位置到相邻位置的横纵坐标变化值。如果题目限制只能是上下左右,这两个数组的长度就都是4;否则默认为8。
收获很小,但也很大,至少解决了对一种题型的恐惧感。
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if n==1:
return 1
if not grid[0][0]==0 or not grid[n-1][n-1]==0:
return -1
visited = [[0]*n for _ in range(n)]
stack = [[0,0]]
visited[0][0] = 1
step = 1
x=[-1,-1,-1,0,0,1,1,1]
y=[-1,0,1,-1,1,-1,0,1]
tmp = []
while len(stack):#第i+1步能走的格子
cur_x,cur_y =stack.pop()
step = visited[cur_x][cur_y]
step += 1
for k in range(8):
next_x = cur_x+x[k]
next_y = cur_y+y[k]
if next_x==n-1 and next_y==n-1:
return step
if 0<=next_x<=n-1 and 0<=next_y<=n-1 and grid[next_x][next_y]==0 and visited[next_x][next_y]==0:
tmp.append([next_x,next_y])
visited[next_x][next_y] = step
if len(stack) ==0:
stack = tmp.copy()
tmp = []
return -1