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算法,初始化队列和访问标记列表,从马的位置开始探索八个方向,当找到牛的位置时返回最短路径步数。通过不断从队列中取出位置进行探索,直到找到目标或队列为空。
-
0
一道走迷宫的题目,位移偏移量用马走日的方式进行。然后因为地图大小150*150,因此选择bfs走迷宫。
#include<bits/stdc++.h> using namespace std; const int N = 155; const int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2}; const int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1}; int n, m; char g[N][N]; int mark[N][N]; int sx, sy, tx, ty; void bfs(){ queue<pair<int, int>> q; q.push({sx, sy}); mark[sx][sy] = 1; while(q.size()){ int x = q.front().first; int y = q.front().second; q.pop(); for(int i=0;i<8;i++){ int a = x + dx[i]; int b = y + dy[i]; if(a < 0 || b < 0) continue; if(a >= n || b >= m) continue; if(g[a][b] == '*' || mark[a][b]) continue; q.push({a, b}); mark[a][b] = mark[x][y] + 1; if(a == tx && b == ty) return ; } } } int main(){ cin>>m>>n; for(int i=0;i<n;i++) cin>>g[i]; for(int i=0;i<n;i++)for(int j=0;j<m;j++) if(g[i][j] == 'K') {sx = i; sy = j;} else if(g[i][j] == 'H') {tx = i; ty = j;} bfs(); cout<<mark[tx][ty] - 1<<endl; return 0; }
- 1
Information
- ID
- 500
- Time
- 1000ms
- Memory
- 256MiB
- Difficulty
- 10
- Tags
- (None)
- # Submissions
- 9
- Accepted
- 3
- Uploaded By