算法提高课-搜索-最短路模型-AcWing 188. 武士风度的牛 :bfs、dist数组记录最小步数
生活随笔
收集整理的这篇文章主要介绍了
算法提高课-搜索-最短路模型-AcWing 188. 武士风度的牛 :bfs、dist数组记录最小步数
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目分析
来源:acwing
分析:马走日,这里用bfs遍历马的行走过程,输出到达终点的最小步数。
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数组记录最小步数的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 算法提高课-搜索-最短路模型-AcWin
- 下一篇: 算法提高课-搜索-最短路模型-AcWin