#42816: python


suyueh (suyueh)

學校 : 不指定學校
編號 : 272111
來源 : [101.12.162.212]
最後登入時間 :
2024-11-10 22:20:41
a982. 迷宮問題#1 | From: [125.229.229.84] | 發表日期 : 2024-10-05 14:00

from collections import deque

def bfs(maze, n):
    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
   
    start = (1, 1)
    end = (n-2, n-2)
   
    queue = deque([(start, 1)])  
    visited = [[False] * n for _ in range(n)]
    visited[1][1] = True
   
    while queue:
        (x, y), dist = queue.popleft()
       
        if (x, y) == end:
            return dist
       
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
           
            if 0 <= nx < n and 0 <= ny < n and maze[nx][ny] == '.' and not visited[nx][ny]:
                visited[nx][ny] = True
                queue.append(((nx, ny), dist + 1))
   
    return "No solution!"

n = int(input())
maze = [input().strip() for _ in range(n)]

result = bfs(maze, n)
print(result)
 
ZeroJudge Forum