4 4 Y.#@ .... .#.. @..M 4 4 Y.#@ .... .#.. @#.M 5 5 Y..@. .#... .#... @..M. #...#
66 88 66
简单的BFS题,bfs来记录Y和M到每个点的最小步数,这里不过要注意可能会有的KFC不能到达
AC代码:
#include <map> #include <set> #include <cmath> #include <deque> #include <queue> #include <stack> #include <cstdio> #include <cctype> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #define LL long long #define INF 0x7fffffff using namespace std; int n, m; int mp[205][205]; int d[205][205]; int vis[205][205]; const int dx[4] = {-1, 0, 1, 0}; const int dy[4] = {0, 1, 0, -1}; struct node { int a; int b; int cnt; node (int x, int y, int z) { a = x; b = y; cnt = z; } }; void bfs(int x, int y) { //bfs遍历来存储M和Y到每个点的距离 memset(vis, 0, sizeof(vis)); queue<node> que; que.push(node(x, y, 0)); vis[x][y] = 1; while(!que.empty()) { node t = que.front(); que.pop(); for(int i = 0; i < 4; i ++) { int xx = t.a + dx[i]; int yy = t.b + dy[i]; if(xx >= 0 && xx <= n - 1 && yy >= 0 && yy <= m - 1 && mp[xx][yy] != 2 && !vis[xx][yy]) { que.push(node(xx, yy, t.cnt + 1)); d[xx][yy] += t.cnt + 1; vis[xx][yy] = 1; } } } } int main() { while(scanf("%d %d", &n, &m) != EOF) { int yx, yy; int mx, my; char s[205]; for(int i = 0; i < n; i ++) { scanf("%s", &s); for(int j = 0; j < m; j ++) { if(s[j] == '.') mp[i][j] = 1; else if(s[j] == '#') mp[i][j] = 2; else if(s[j] == '@') { mp[i][j] = 3; } else if(s[j] == 'Y') { mp[i][j] = 4; yx = i; yy = j; } else if(s[j] == 'M') { mp[i][j] = 4; mx = i; my = j; } } } // for(int i = 0; i < n; i ++, cout << endl) { // for(int j = 0; j < m; j ++) { // cout << mp[i][j] << " "; // } // } memset(d, 0, sizeof(d)); bfs(yx, yy); bfs(mx, my); int ans = INF; for(int i = 0; i < n; i ++) { for(int j = 0; j < m; j ++) { if(mp[i][j] == 3) { if(d[i][j] != 0) { //要注意还有可能有的KFC不能到达 ans = min(ans, d[i][j]); } } } } printf("%d\n", ans * 11); } return 0; }