欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

算法提高课-搜索-最短路模型-AcWing 188. 武士风度的牛 :bfs、dist数组记录最小步数

发布时间:2025/4/5 编程问答 43 豆豆
生活随笔 收集整理的这篇文章主要介绍了 算法提高课-搜索-最短路模型-AcWing 188. 武士风度的牛 :bfs、dist数组记录最小步数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目分析



来源:acwing

分析:马走日,这里用bfs遍历马的行走过程,输出到达终点的最小步数。

  • 使用bfs求到每个点的最小步数,需要开一个dist[][]数组,来记录起点到某点的最小步数。
  • 队列里面需要判断很多东西,容易忘记的是:已经遍历过的点直接continue,遍历过的点是dist[][] != -1.
  • 当找到终点时,直接return dist[t.x][t.y] + 1;
  • ac代码

    #include<bits/stdc++.h> #define x first #define y second using namespace std; const int N = 200, M = N * N; typedef pair<int,int> PII; PII q[M]; int n,m; char g[N][N]; int dist[N][N]; // 记录最短步数 int bfs(int sx, int sy){int dx[8] = {-2, -1, 1, 2, 2, 1, -1, -2};int dy[8] = {1, 2, 2, 1, -1, -2, -2, -1};memset(dist, -1, sizeof dist);int hh = 0, tt = 0;q[hh] = {sx,sy};dist[sx][sy] = 0;int cnt = 0;while( hh <= tt){PII t = q[hh ++];for(int i = 0; i < 8; i++){int a = t.x + dx[i], b = t.y+ dy[i];if( a < 0 || a >= n || b < 0 || b >= m) continue;if(g[a][b] == '*') continue;if(dist[a][b] != -1) continue;if(g[a][b] == 'H') return dist[t.x][t.y] + 1;dist[a][b] = dist[t.x][t.y] + 1;q[++ tt] = {a, b};}}return -1; }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'){cout <<bfs(i, j);}}

    题目来源

    https://www.acwing.com/problem/content/190/

    总结

    以上是生活随笔为你收集整理的算法提高课-搜索-最短路模型-AcWing 188. 武士风度的牛 :bfs、dist数组记录最小步数的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。