http://acm.hdu.edu.cn/showproblem.php?pid=2612
Two BFs, record the shortest time for each KFC. Select the shortest time.
#include <stdio.h> #include <iostream> #include <string> #include <cstring> #include <cmath > #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <set > #include <map> #include <vector>using namespace std;int N, m;int dir[4][2] = {{1, 0}, {-1, 0}, {0, 1 }, {0,-1}};int Check (int x, int y) {if (x >= 1 && x <= n && y >= 1 && y <= m) return 1;return 0;} struct Node{int x;int y;int t1, T2;char c;} P[210][210];int vis[210][210];int SX, Sy;int ex, ey;void bfs (int x,int y) {memset (vis,0,sizeof (Vis)); Queue<node> Q ; node QQ, qqq;qq.x = X;QQ.Y = Y;qq.t1 = 0;p[x][y].t1 = 0;vis[x][y] = 1;q.push (QQ), while (!q.empty ()) {QQ = Q.front (); Q.pop ( ); for (int i = 0; i < 4; i++) {int x = qq.x + Dir[i][0];int y = qq.y + dir[i][1];if (!check (x, y) | | vis[x][y] | | p[x][y ].C = = ' # ') continue;vis[x][y] = 1;qqq.x = X;qqq.y = Y;qqq.t1 = qq.t1 + 1; P[x][y].t1 = Qqq.t1;q.push (QQQ);}}return;} void bfs1 (int x, int y) {memset (Vis, 0, sizeof (VIS));queue<node> q;node qq, qqq;qq.x = X;QQ.Y = Y;qq.t2 = 0;p[x][y].t 2 = 0;vis[x][y] = 1;q.push (QQ), while (!q.empty ()) {QQ = Q.front (), Q.pop (); for (int i = 0; i < 4; i++) {int x = qq.x + dir I [0];int y = qq.y + dir[i][1];if (!check (x, y) | | vis[x][y] | | p[x][y].c = = ' # ') continue;vis[x][y] = 1;qqq.x = X;qqq.y = y; Qqq.t2 = qq.t2 + 1;p[x][y].t2 = Qqq.t2;q.push (QQQ);}} return;} int main () {while (CIN >> n >> m) {GetChar (), for (int i = 1, i <= N; i++) {for (int j = 1; j <= M; j + +) {cin >> p[i][j].c;if (p[i][j].c = = ' Y ') {sx = I;sy = j;} if (p[i][j].c = = ' M ') {ex = I;ey = j;}} GetChar ();} BFS (Sx,sy); BFS1 (Ex,ey); for (int i = 1, i <= N; i++) for (int j = 1; j <= M; j + +) {if (p[i][j].c = = ' @ ') {p[i][j].t1 = ( P[I][J].T1+P[I][J].T2);}} int ans = 10000000;for (int i = 1; I <= n; i++) for (int j = 1; j <= M; j + +) {if (p[i][j].c = = ' @ ') {ans = min (p[i][j]). T1, ans);}} Ans *= 11;cout << ans << endl;} return 0;}
hdu-2612 two times BFS