bfs预处理一点到边界的最小距离,IDA*求出可行方案。注意按字典序初始化dir数组。并且存在中间点全为1,边界含0的可能性(wa了很多次)。此时不输出任何命令。
/* 1813 */
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std; #define MAXN 80
#define INF 0xffffff int n, m;
char ops[][] = {
"east",
"north",
"south",
"west"
};
int op[];
int x[MAXN], y[MAXN];
int dis[][];
int visit[][];
char map[][];
int dir[][] = {
,,-,,,,,-
}; inline bool isEnd(int x, int y) {
return x== || x==n- || y== || y==n-;
} inline bool check(int x, int y) {
return x< || x>=n || y< || y>=n;
} int bfs(int x, int y) {
int xx, yy;
int i, j, k;
queue<int> Q; k = *x + y;
Q.push(k);
memset(visit, -, sizeof(visit));
visit[x][y] = ; while (!Q.empty()) {
k = Q.front();
Q.pop();
x = k/;
y = k%;
for (i=; i<; ++i) {
xx = x + dir[i][];
yy = y + dir[i][];
if (map[xx][yy]=='' || visit[xx][yy]>=)
continue;
visit[xx][yy] = visit[x][y]+;
if (isEnd(xx, yy))
return visit[xx][yy];
k = *xx + yy;
Q.push(k);
}
}
return ;
} bool dfs(int d, int *px, int *py) {
int mmax = -;
int x[MAXN], y[MAXN];
int i, j, k; for (i=; i<m; ++i)
mmax = max(mmax, dis[px[i]][py[i]]);
if (mmax > d)
return false;
if (d == )
return true; for (i=; i<; ++i) {
op[d] = i;
for (j=; j<m; ++j) {
x[j] = px[j] + dir[i][];
y[j] = py[j] + dir[i][];
if (isEnd(px[j], py[j]) || map[x[j]][y[j]]=='') {
x[j] = px[j];
y[j] = py[j];
}
}
if (dfs(d-, x, y))
return true;
}
return false;
} int main() {
int t = ;
int i, j, k; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif while (scanf("%d",&n) != EOF) {
m = ;
for (i=; i<n; ++i)
scanf("%s", map[i]);
for (i=; i<n; ++i) {
for (j=; j<n; ++j) {
if (map[i][j] == '') {
dis[i][j] = INF;
} else {
if (isEnd(i, j)) {
dis[i][j] = ;
} else {
dis[i][j] = bfs(i, j);
x[m] = i;
y[m] = j;
++m;
}
}
}
}
if (t++)
printf("\n");
if (m) {
for (i=; ; ++i) {
if (dfs(i, x, y))
break;
}
for (j=i; j>; --j)
printf("%s\n", ops[op[j]]);
}
} return ;
}