# n,m=map(int,input().split()) # g=[list(map(int,input().split())) for i in range(n)] # flag=[[1]*m for _ in range(n)] # x1,y1,x2,y2=map(lambda x:int(x)-1,input().split()) # class Node: # def __init__(self,x,y,val,cnt): # self.x=x # self.y=y # self.val=val # self.cnt=cnt # q=[Node(x1,y1,g[x1][y1],0)] # ans=0xfffffffff # # print(ans) # while q: # node=q[0] # # print(node.x,node.y) # del q[0] # # q.pop(0) # if node.x==x2 and node.y==y2: # ans=min(node.cnt,ans) # for a,b in [[0,1],[0,-1],[-1,0],[1,0]]: #右左下上 # if 0<=node.y+b<m and 0<=node.x+a<n and g[node.x+a][node.y+b] and flag[node.x+a][node.y+b]: # q.append(Node(node.x+a,node.y+b,g[node.x+a][node.y+b],node.cnt+1)) # flag[node.x+a][node.y+b]=0 # print(-1 if ans==0xfffffffff else ans)
# 看了题解后改进自己的 n, m = map(int, input().split()) g = [list(map(int, input().split())) for i inrange(n)] x1, y1, x2, y2 = map(lambda x: int(x) - 1, input().split()) q = [[x1, y1, 0]] while q: x, y, cnt = q.pop(0) if x == x2 and y == y2: print(cnt) break for a, b inmap(lambda i:(i[0] + x, i[1] + y),((0, 1), (0, -1), (-1, 0), (1, 0))): # 右左下上 if0 <= a < n and0 <= b < m and g[a][b]: q.append((a, b, cnt + 1)) g[a][b] = 0 else: print(-1) """ 结合地图进行dfs,一开始起点进队列,队列不为空时进行循环,每次循环,队列首出队列,然后往上下左右四个方向走,超过地图大小或是阻碍或走过了就不入队列,原本用的class用inf记录步数,后来看题解: 可以用三元组,一开始头节点的出队列可以直接用pop(0)接收,再分给三个变量记录,最后走到了终点直接输出break否则输出-1 当然,最妙的在于走过的直接赋值地图的值为0表示走过了,这样就不用再走了,也不用开标志数组了,与原来地图的阻碍同义 """