2 solutions
-
0
from collections import deque # 获取输入信息 C, R = map(int, input().split()) # 绘制地图 graph = [] for _ in range(R): row = input() graph.append(row) for r in range(R): for c in range(C): if graph[r][c] == 'K': start_x, start_y = r, c # 偏移量 dx = [-2, -1, 1, 2, 2, 1, -1, -2] dy = [1, 2, 2, 1, -1, -2, -2, -1] def bfs(): queue = deque([(start_x, start_y, 0)]) visited = [[False] * C for _ in range(R)] visited[start_x][start_y] = True while queue: x, y, step = queue.popleft() if graph[x][y] == 'H': return step for i in range(8): new_x = x + dx[i] new_y = y + dy[i] if 0 <= new_x < R and 0 <= new_y < C and not visited[new_x][new_y] and graph[new_x][new_y]!= '*': visited[new_x][new_y] = True queue.append((new_x, new_y, step + 1)) print(bfs())
首先读取农场的列数和行数以及地图信息,找到马的起始位置。然后采用BFS算法,初始化队列和访问标记列表,从马的位置开始探索八个方向,当找到牛的位置时返回最短路径步数。通过不断从队列中取出位置进行探索,直到找到目标或队列为空。
Information
- ID
- 500
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 10
- Tags
- (None)
- # Submissions
- 9
- Accepted
- 3
- Uploaded By