在一行上输入两个整数
,代表网格的行数与列数。
在一行上输入四个整数
,代表起点与终点的坐标。
此后
行,第
行输入一个长度为
的字符串
,其中
若
,表示第
行第
列为障碍物;
若
,表示该格子可通行。
保证起点所在格子可通行。
输出一个整数,表示最少移动次数;若无法到达,输出
。
5 5 1 1 5 5 ..... ****. ..... **.** .....
12
5 5 1 1 4 5 ..... ****. ..... **.** .....
-1
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