首页 > 试题广场 >

走迷宫

[编程题]走迷宫
  • 热度指数:15289 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
\hspace{15pt}给定一个 n \times m 的网格。你从起点 (x_s, y_s) 出发,每一次可以向上、下、左、右移动一步(若不超出边界)。某些格子上存在障碍物,无法经过。求从 (x_s, y_s) 移动到终点 (x_t, y_t) 的最少步数;若无法到达,输出 -1

输入描述:
\hspace{15pt}在一行上输入两个整数 n, m \left(1 \leqq n, m \leqq 1000\right),代表网格的行数与列数。
\hspace{15pt}在一行上输入四个整数 x_s, y_s, x_t, y_t \left(1 \leqq x_s, x_t \leqq n;\ 1 \leqq y_s, y_t \leqq m\right),代表起点与终点的坐标。
\hspace{15pt}此后 n 行,第 i 行输入一个长度为 m 的字符串 g_i,其中
\hspace{23pt}\bullet\,g_{i, j}=\texttt{,表示第 i 行第 j 列为障碍物;
\hspace{23pt}\bullet\,g_{i, j}=\texttt{,表示该格子可通行。
\hspace{15pt}保证起点所在格子可通行。


输出描述:
\hspace{15pt}输出一个整数,表示最少移动次数;若无法到达,输出 -1
示例1

输入

5 5
1 1 5 5
.....
****.
.....
**.**
.....

输出

12
示例2

输入

5 5
1 1 4 5
.....
****.
.....
**.**
.....

输出

-1
示例3

输入

5 5
1 1 5 5
.....
****.
.....
*****
.....

输出

-1
import sys
from collections import deque

try:
    while True:
        n, m = map(int, sys.stdin.readline().split())

        start_x, start_y, end_x, end_y = map(int, sys.stdin.readline().split())

        grid = []
        for _ in range(n):
            line = sys.stdin.readline().strip()
            grid.append(line)

        direction = [(1,0), (0, 1), (-1, 0), (0 , -1)]
        visited = [[False] * m for _ in range(n)]
        queue = deque()
        queue.append((start_x - 1, start_y - 1, 0))
        visited[start_x - 1][start_y - 1] = True
        find_result = False
        while queue:
            x, y, step = queue.popleft()
            if x == end_x - 1 and y == end_y - 1:
                print(step)
                find_result = True

            else:
                for dx, dy in direction:
                    next_x, next_y = dx + x, dy + y
                    if 0 <= next_x < n and 0 <= next_y < m and grid[next_x][next_y] != "*" and not visited[next_x][next_y]:
                        visited[next_x][next_y] = True
                        queue.append((next_x, next_y, step + 1))

        if not find_result:
            print(-1)

except:
    pass

发表于 2025-03-06 16:03:38 回复(0)