#46681: 用bfs


shps104227hello@gmail.com (?)

學校 : 不指定學校
編號 : 159330
來源 : [1.34.124.150]
最後登入時間 :
2025-06-16 23:40:04

用bfs

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python:

from collections import deque
n,m = map(int,input().split())
test = ["#####",
        "# # #",
        "# # #",
        "#   #",
        "#####"]
d = [(0,-1),(0,1),(1,0),(-1,0)]
arr = []
for i in range(n):
    arr.append(list(input()))

x1,y1 = 1,1 #開始座標
x2,y2 = n-2,m-2 #結束座標
dist = [[-1]*n for _ in range(m)] #距離紀錄
dist[x1][y1] = 0
q = deque([(x1,y1)])
while q:
    x,y = q.popleft()
    for dx,dy in d:
        nx = dx + x
        ny = dy + y
        if (x,y) == (x2,y2): #如果到達終點
           break #提早結束BFS
        if 0 <= nx < n\
             and 0 <= ny < m\
              and arr[nx][ny] != "#"\
               and dist[nx][ny] == -1:
            dist[nx][ny] = 1 + dist[x][y]
            q.append((nx,ny)) #加入鄰居作為下一步
print(dist[x2][y2])