bfs预处理一点到边界的最小距离,IDA*求出可行方案。注意按字典序初始化dir数组。并且存在中间点全为1,边界含0的可能性(wa了很多次)。此时不输出任何命令。
1 /* 1813 */ 2 #include <iostream> 3 #include <queue> 4 #include <algorithm> 5 #include <cstdio> 6 #include <cstring> 7 #include <cstdlib> 8 using namespace std; 9 10 #define MAXN 80 11 #define INF 0xffffff 12 13 int n, m; 14 char ops[4][6] = { 15 "east", 16 "north", 17 "south", 18 "west" 19 }; 20 int op[1005]; 21 int x[MAXN], y[MAXN]; 22 int dis[9][9]; 23 int visit[9][9]; 24 char map[9][9]; 25 int dir[4][2] = { 26 0,1,-1,0,1,0,0,-1 27 }; 28 29 inline bool isEnd(int x, int y) { 30 return x==0 || x==n-1 || y==0 || y==n-1; 31 } 32 33 inline bool check(int x, int y) { 34 return x<0 || x>=n || y<0 || y>=n; 35 } 36 37 int bfs(int x, int y) { 38 int xx, yy; 39 int i, j, k; 40 queue<int> Q; 41 42 k = 10*x + y; 43 Q.push(k); 44 memset(visit, -1, sizeof(visit)); 45 visit[x][y] = 0; 46 47 while (!Q.empty()) { 48 k = Q.front(); 49 Q.pop(); 50 x = k/10; 51 y = k%10; 52 for (i=0; i<4; ++i) { 53 xx = x + dir[i][0]; 54 yy = y + dir[i][1]; 55 if (map[xx][yy]=='1' || visit[xx][yy]>=0) 56 continue; 57 visit[xx][yy] = visit[x][y]+1; 58 if (isEnd(xx, yy)) 59 return visit[xx][yy]; 60 k = 10*xx + yy; 61 Q.push(k); 62 } 63 } 64 return 0; 65 } 66 67 bool dfs(int d, int *px, int *py) { 68 int mmax = -1; 69 int x[MAXN], y[MAXN]; 70 int i, j, k; 71 72 for (i=0; i<m; ++i) 73 mmax = max(mmax, dis[px[i]][py[i]]); 74 if (mmax > d) 75 return false; 76 if (d == 0) 77 return true; 78 79 for (i=0; i<4; ++i) { 80 op[d] = i; 81 for (j=0; j<m; ++j) { 82 x[j] = px[j] + dir[i][0]; 83 y[j] = py[j] + dir[i][1]; 84 if (isEnd(px[j], py[j]) || map[x[j]][y[j]]=='1') { 85 x[j] = px[j]; 86 y[j] = py[j]; 87 } 88 } 89 if (dfs(d-1, x, y)) 90 return true; 91 } 92 return false; 93 } 94 95 int main() { 96 int t = 0; 97 int i, j, k; 98 99 #ifndef ONLINE_JUDGE 100 freopen("data.in", "r", stdin); 101 freopen("data.out", "w", stdout); 102 #endif 103 104 while (scanf("%d",&n) != EOF) { 105 m = 0; 106 for (i=0; i<n; ++i) 107 scanf("%s", map[i]); 108 for (i=0; i<n; ++i) { 109 for (j=0; j<n; ++j) { 110 if (map[i][j] == '1') { 111 dis[i][j] = INF; 112 } else { 113 if (isEnd(i, j)) { 114 dis[i][j] = 0; 115 } else { 116 dis[i][j] = bfs(i, j); 117 x[m] = i; 118 y[m] = j; 119 ++m; 120 } 121 } 122 } 123 } 124 if (t++) 125 printf(" "); 126 if (m) { 127 for (i=1; ; ++i) { 128 if (dfs(i, x, y)) 129 break; 130 } 131 for (j=i; j>0; --j) 132 printf("%s ", ops[op[j]]); 133 } 134 } 135 136 return 0; 137 }