FAFU- 1387 Astar寻妹纸 a*

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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值