本文主要是介绍N - Find a way HDU - 2612(BFS),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
Sample Input
4 4
Y.#@
…
.#…
@…M
4 4
Y.#@
…
.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#
Sample Output
66
88
66
思路:基础BFS,BFS跑一遍算出到每个人到各个KFC的距离,再枚举距离求距离和最小。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>using namespace std;
const int maxn = 200 + 10;
int dr[] = {-1,1,0,0};
int dc[] = {0,0,-1,1};
int n,m;
int sx,sy,ex,ey;
char maze[maxn][maxn];
int dis[2][maxn][maxn];
int dirx[] = {1,-1,0,0};
int diry[] = {0,0,-1,1};
struct node
{int x,y;node(){}node(int x,int y):x(x),y(y){}
};void bfs(int x,int y,int type)
{memset(dis[type],-1,sizeof(dis[type]));queue<node>Q;Q.push(node(x,y));dis[type][x][y] = 0;while(!Q.empty()){node now = Q.front();Q.pop();for(int i = 0;i < 4;i++){int nx = now.x + dirx[i];int ny = now.y + diry[i];if(nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != '#' && dis[type][nx][ny] == -1){dis[type][nx][ny] = dis[type][now.x][now.y] + 1;Q.push(node(nx,ny));}}}
}int main()
{while(~scanf("%d%d",&n,&m)){vector<node>KFC;for(int i = 0;i < n;i++){scanf("%s",maze[i]);for(int k = 0;k < m;k++){if(maze[i][k] == 'Y'){sx = i,sy = k;}else if(maze[i][k] == 'M'){ex = i,ey = k;}else if(maze[i][k] == '@'){KFC.push_back(node(i,k));}}}bfs(sx,sy,0);bfs(ex,ey,1);int minn = 1e8;for(int i = 0;i < KFC.size();i++){int len1 = dis[0][KFC[i].x][KFC[i].y];int len2 = dis[1][KFC[i].x][KFC[i].y];if(len1 == -1 || len2 == -1){continue;}int length = len1 + len2;minn = min(minn,length);}printf("%d\n",minn * 11);}return 0;
}
这篇关于N - Find a way HDU - 2612(BFS)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!