简单BFS
http://acm.fzu.edu.cn/problem.php?pid=2150
/************************************************ * Author :Powatr * Created Time :2015-8-23 12:33:32 * File Name :J.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int MAXN = 1e5 + 10; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; int dirx[] = {1, -1, 0, 0}; int diry[] = {0, 0, 1, -1}; struct edge1{ int x, y, t; }; queue<edge1> q; struct edge{ int x, y; } a[200]; int vis[11][11]; char mp[11][11]; int n, m; int ok(int x, int y){ if(x>= 1 && x <= n && y >= 1 && y <= m && !vis[x][y] && mp[x][y] == '#') return true; return false; } int main(){ int T; scanf("%d", &T); for(int cas = 1; cas <= T;cas++){ memset(mp, 0, sizeof(mp)); memset(a, 0, sizeof(a)); scanf("%d%d", &n, &m); for(int i = 1; i <= n; i++){ scanf("%s", mp[i] + 1); } int cout = 0; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(mp[i][j] == '#'){ a[++cout].x = i; a[cout].y = j; } } } int Time = INF; if(cout <= 2) { printf("Case %d: 0 ", cas); continue; } for(int i = 1; i <=cout ;i++){ for(int j = i + 1; j <= cout; j++){ int time = 0; memset(vis, 0, sizeof(vis)); vis[a[i].x][a[i].y] = vis[a[j].x][a[j].y] = 1; while(!q.empty()) q.pop(); q.push((edge1){a[i].x, a[i].y, 0}); q.push((edge1){a[j].x, a[j].y, 0}); while(!q.empty()){ edge1 now = q.front(); q.pop(); int dx = now.x; int dy = now.y; int tt = now.t; time = max(time, tt); int sx, sy; for(int i = 0 ; i < 4; i++){ sx = dx + dirx[i]; sy = dy + diry[i]; if(ok(sx,sy)){ vis[sx][sy] = 1; q.push((edge1){sx, sy, tt+1}); } } } int flag = 0; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(mp[i][j] == '#' && vis[i][j] == 0){ flag = 1; break; } } } if(!flag) Time = min(Time, time); } } int flag = 0; printf("Case %d: ", cas); if(Time == INF) puts("-1"); else printf("%d ", Time ); } return 0; }