最近主要在学习java,刷题比较少。
这道题利用了BFS算法,其中这道题他有两个起点,我们可以分别对两个起点进行bfs算法求解,然后找出两个起点到某一个kfc的最小值,再乘以11即可。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int inf = 0x3f3f3f3f;
int n, m, cnt;
char mp[220][220];
bool vis[220][220];
int a[220][220];
int b[220][220];
int d[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
struct node
{
int x, y, step;
};
void bfs(int x, int y, int l[220][220])
{
memset(vis, 0, sizeof(vis));
queue<node> q;
node a, ne;
a.x = x; a.y = y; a.step = 0;
q.push(a);
vis[x][y] = 1;
while(!q.empty())
{
a = q.front();
q.pop();
if(mp[a.x][a.y] == '@')
{
l[a.x][a.y] = a.step;
}
for(int i = 0; i < 4; i++)
{
ne.x = a.x + d[i][0];
ne.y = a.y + d[i][1];
if(ne.x < 0 || ne.x >= n || ne.y < 0 || ne.y >= m || vis[ne.x][ne.y] == 1 || mp[ne.x][ne.y] == '#')
continue;
ne.step = a.step + 1;
q.push(ne);
vis[ne.x][ne.y] = 1;
}
}
return;
}
int main()
{
int i, j, be1, en1, be2, en2, sum;
while(scanf("%d%d", &n, &m) != EOF)
{
sum = inf;
cnt = 0;
for(i = 0; i < n; i++)
{
scanf("%s", &mp[i]);
for(j = 0; j < m; j++)
{
if(mp[i][j] == 'Y')
{
be1 = i;
en1 = j;
}
else if(mp[i][j] == 'M')
{
be2 = i;
en2 = j;
}
}
}
bfs(be1, en1, a);
bfs(be2, en2, b);
for(i = 0; i < n; i++){
for(j = 0; j < m; j++){
if(mp[i][j] == '@' && vis[i][j] == 1)
{
sum = min(sum, a[i][j]+b[i][j]);
}
}
}
printf("%d\n", sum*11);
}
return 0;
}