h()为当前所有点到边界的最小步数的 最大值
要用bfs预处理下每个点到边界的最小距离,只就用直线距离会错
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define MAX 0x3f3f3f3f
struct Point{
int x, y;
};
struct Node{
int x, y;
int step;
};
char maps[10][10];
Point point[64];
int mindis[11][11];
int N;
int tot;
int maxdeep;
int record[200];
char out[][10] = { "east", "north", "south", "west" };
int moves[][2] = { { 0, 1 }, { -1, 0 }, { 1, 0 }, { 0, -1 } };
bool check(){
for( int i = 0; i < tot; i++ ){
if( point[i].x == 0 || point[i].x == N - 1 || point[i].y == 0 || point[i].y == N - 1 ){
continue;
}else{
return false;
}
}
return true;
}
int h(){
int ans = 0;
for( int i = 0; i < tot; i++ ){
ans = max( ans, mindis[point[i].x][point[i].y] );
}
return ans;
}
int BFS( int x, int y ){
bool mark[11][11];
queue<Node> q;
Node start;
start.x = x;
start.y = y;
start.step = 0;
q.push( start );
memset( mark, false, sizeof( mark ) );
mark[start.x][start.y] = true;
while( !q.empty() ){
Node p = q.front();
q.pop();
if( p.x == 0 || p.x == N - 1 || p.y == 0 || p.y == N - 1 ){
return p.step;
}
for( int i = 0; i < 4; i++ ){
Node temp = p;
temp.x += moves[i][0];
temp.y += moves[i][1];
temp.step++;
if( maps[temp.x][temp.y] == '1' || mark[temp.x][temp.y] ){
continue;
}
q.push( temp );
mark[temp.x][temp.y] = true;
}
}
return 0;
}
bool DFS( int deep ){
if( deep == maxdeep ){
return check();
}
if( deep + h() > maxdeep ){
return false;
}
for( int i = 0; i < 4; i++ ){
record[deep] = i;
bool temp[64] = { false };
for( int j = 0; j < tot; j++ ){
if( point[j].x == 0 || point[j].x == N - 1 || point[j].y == 0 || point[j].y == N - 1 ){
temp[j] = false;
}else if( maps[point[j].x+moves[i][0]][point[j].y+moves[i][1]] == '1' ){
temp[j] = false;
}else{
temp[j] = true;
}
}
for( int j = 0; j < tot; j++ ){
if( !temp[j] ){
continue;
}
point[j].x += moves[i][0];
point[j].y += moves[i][1];
}
if( DFS( deep + 1 ) ){
return true;
}
for( int j = 0; j < tot; j++ ){
if( !temp[j] ){
continue;
}
point[j].x -= moves[i][0];
point[j].y -= moves[i][1];
}
}
return false;
}
int main(){
int flag = 0;
while( scanf( "%d", &N ) != EOF ){
if( flag ){
cout << endl;
}else{
flag = 1;
}
tot = 0;
for( int i = 0; i < N; i++ ){
scanf( "%s", maps[i] );
for( int j = 0; j < N; j++ ){
if( i == 0 || i == N - 1 || j == 0 || j == N - 1 ){
continue;
}
if( maps[i][j] == '0' ){
point[tot].x = i;
point[tot++].y = j;
}
}
}
memset( mindis, 0, sizeof( mindis ) );
for( int i = 0; i < tot; i++ ){
mindis[point[i].x][point[i].y] = BFS( point[i].x, point[i].y );
}
maxdeep = 0;
while( 1 ){
if( DFS( 0 ) ){
break;
}
maxdeep++;
}
for( int i = 0; i < maxdeep; i++ ){
cout << out[record[i]] << endl;
}
}
return 0;
}