算法提高课-搜索-最短路模型-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