http://acm.fafu.edu.cn/problem.php?id=1387
#include<stdio.h>
#include<cmath>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 410;
const int inf = 1<<29;
int n,m;
int map[maxn][maxn];
int xs[] = {0,1,1,1,0,-1,-1,-1};
int ys[] = {1,1,0,-1,-1,-1,0,1};
struct node
{
int x,y;
int t,h,g,f; // t步数 h几何距离 g移动距离 f f = h + g;
bool operator < ( const node &k ) const
{
return f > k.f;
}
};
node s,e;
int getdis( node x ) //求几何距离
{
return ( abs(x.x-e.x) + abs(x.y-e.y) )*10;
}
bool ok( node x ,int i) //判断对角
{
if( !map[x.x + xs[i-1]][x.y + ys[i-1]] )
return false;
if( i == 7 && !map[x.x][x.y+1])
return false;
if( i != 7 && !map[x.x + xs[i+1]][x.y + ys[i+1]] )
return false;
return true;
}
int Astar( node s,node e )
{
node cnt,pos;
priority_queue <node> que;
s.t = 0; s.h = getdis(s); s.g = 0; s.f = s.h + s.g;
que.push(s);
while( !que.empty() )
{
cnt = que.top(); que.pop();
map[cnt.x][cnt.y] = 0; //走过的点置零
if( cnt.x == e.x && cnt.y == e.y ) //找到终点 输出步数
return cnt.t;
for( int i = 0; i < 8; i ++ )
{
pos.x = cnt.x + xs[i];
pos.y = cnt.y + ys[i];
if( map[pos.x][pos.y] && pos.x >= 1 && pos.y <= n && pos.x >= 1 && pos.y <= m )
{
if( i % 2 ) //为对角方向
if( ok(cnt,i) ) //判断对角能否走
pos.g = cnt.g + 14;
else continue;
else
pos.g = cnt.g + 10;
pos.t = cnt.t + 1;
pos.h = getdis(pos);
pos.f = pos.h + pos.g;
que.push( pos );
}
}
}
return 1;
}
int main()
{
//freopen("data.txt","r",stdin);
while( scanf("%d%d",&m,&n) == 2 )
{
for( int i = 1; i <= n; i ++ )
{
for( int j = 1; j <= m; j ++ )
{
scanf("%1d",&map[i][j]);
}
}
scanf("%d%d%d%d",&s.y,&s.x,&e.y,&e.x);
s.x++;s.y++;e.x++;e.y++;
int ans = Astar( s,e );
printf("%d\n",ans-1);
}
return 0;
}