直接bfs就可以了。奇怪的是竟然跑出了0ms。
值得注意的是距离最近的不一定就是segments最少的,所以bfs的时候不能搜到一个解就退出。应该搜到queue为空。
/* * Author: stormdpzh * Created Time: 2013/3/12 13:42:23 * File Name: poj_1101.cpp */ #include <iostream> #include <cstdio> #include <sstream> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <list> #include <algorithm> #include <functional> #define sz(v) ((int)(v).size()) #define rep(i, n) for(int i = 0; i < n; i++) #define repf(i, a, b) for(int i = a; i <= b; i++) #define repd(i, a, b) for(int i = a; i >= b; i--) #define out(n) printf("%d\n", n) #define mset(a, b) memset(a, b, sizeof(a)) #define lint long long using namespace std; const int INF = 1 << 30; const int MaxN = 85; const int dir_x[4] = {0, 1, 0, -1}; const int dir_y[4] = {-1, 0, 1, 0}; struct Node { int x, y; int seg; int dir; }; queue<Node> que; int maz[MaxN][MaxN]; int vis[MaxN][MaxN]; int w, h; int xx1, yy1; int xx2, yy2; char s[MaxN]; int res; bool is_in_board(int x, int y) { if(x >= 0 && x <= w + 1 && y >= 0 && y <= h + 1) return true; return false; } void gao() { res = -1; while(!que.empty()) que.pop(); mset(vis, 0); vis[xx1][yy1] = true; Node tmp; tmp.x = xx1; tmp.y = yy1; tmp.seg = 0; tmp.dir = -1; que.push(tmp); while(!que.empty()) { tmp = que.front(); que.pop(); if(tmp.x == xx2 && tmp.y == yy2) { if(res == -1 || tmp.seg < res) { res = tmp.seg; } continue ; } rep(i, 4) { int x = tmp.x + dir_x[i]; int y = tmp.y + dir_y[i]; if(is_in_board(x, y) && (!vis[x][y] || vis[x][y] > tmp.seg + 1) && (maz[x][y] == 1 || (x == xx2 && y == yy2))) {// && (tmp.x != xx1 || tmp.y != yy1)))) { vis[x][y] = tmp.seg + 1; Node tmp1; tmp1.x = x; tmp1.y = y; tmp1.seg = tmp.seg + (i == tmp.dir ? 0 : 1); tmp1.dir = i; que.push(tmp1); } } } } int main() { int boa = 1; while(2 == scanf("%d%d", &w, &h) && (w || h)) { rep(i, MaxN) rep(j, MaxN) { maz[i][j] = 1; } getchar(); repf(i, 1, h) { gets(s + 1); repf(j, 1, w) { maz[j][i] = (s[j] == 'X' ? 0 : 1); } } printf("Board #%d:\n", boa++); int cnt = 1; while(4 == scanf("%d%d%d%d", &xx1, &yy1, &xx2, &yy2)) { if(xx1 == 0 && yy1 == 0 && xx2 == 0 && yy2 == 0) break; gao(); printf("Pair %d: ", cnt++); if(res > 0) { printf("%d segments.\n", res); } else { printf("impossible.\n"); } } puts(""); } return 0; }