题意:Y和M到达同一个@的时间最短的时间。
求最短距离用bfs
vis初始化为无限大
对Y bfs求到所有@的最短距离 记录到vis[0][][]数组中
对M bfs求到所有@的最短距离 记录到vis[1][][]数组中
在求到@最短的时间。
#include
#include
#include
#include
using namespace std;
const int N = 222;
char str[N][N];
int n, m;
struct node
{
int x, y;
node(){}
node(int xx, int yy)
{
x = xx; y = yy;
}
};
int vis[2][N][N];
int dir[5][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
queue
que; void bfs(node star, int cnt) { while(!que.empty()) que.pop(); que.push( star ); vis[cnt][star.x][star.y] = 0; while(!que.empty()) { node tmp = que.front(); que.pop(); // printf("tmp.x=%d \t tmp.y=%d tmp.val=%d\n", tmp.x, tmp.y, vis[cnt][tmp.x][tmp.y]); int x, y; for(int i = 0; i < 4; i++) { x = tmp.x + dir[i][0]; y = tmp.y + dir[i][1]; if(0 <= x && x < n && 0 <= y && y < m && (str[x][y] == '.' || str[x][y] == '@') && vis[cnt][x][y] == N*N*N) { vis[cnt][x][y] = vis[cnt][tmp.x][tmp.y]+1; que.push( node(x, y) ); // printf("\t x=%d \t y=%d \t vis[cnt][x][y]=%d\n", x, y, vis[cnt][x][y]); } } } } int main(void) { while(~scanf("%d%d", &n, &m)) { int i, j; node star1, star2; for(i = 0; i < n; i++) { scanf("%s", str[i]); for(j = 0; str[i][j]; j++) { if(str[i][j] == 'Y') { star1 = node(i, j); } if(str[i][j] == 'M') { star2 = node(i, j); } vis[0][i][j] = vis[1][i][j] = N*N*N; } } bfs(star1, 0); bfs(star2, 1); int ans = N*N*N; for(i = 0; i < n; i++) { for(j = 0; j < m; j++) { if(str[i][j] == '@') ans = min(ans, vis[0][i][j]+vis[1][i][j]); } } printf("%d\n", ans*11); } return 0; }