【Bfs】HDU 1026 Ignatius and the Princess I

直接贴代码好了。。。感觉Bfs的重点只是在于理清


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>

using namespace std;

int n,m,cont;
char mp[105][105];          //记录地图
struct
{
    int x,y,d;
    int before;
}q[10000007],s,now;
bool vis[105][105];
int xx,yy;

int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};        //方向数组

bool judge(int x,int y)
{
    if(x>=0 && x<n && y>=0 && y<m && mp[x][y]!='X') return true;
    return false;
}                   //判定墙壁和出界

void print(int n)
{
    if(q[n].before==-1)
    {
        xx=0;
        yy=0;
        return;
    }
    print(q[n].before);
    printf("%ds:",cont++);
    if(xx==q[n].x && yy==q[n].y) printf("FIGHT AT (%d,%d)\n",xx,yy);
    else
    {
        printf("(%d,%d)->(%d,%d)\n",xx,yy,q[n].x,q[n].y);
        xx=q[n].x;
        yy=q[n].y;
    }
}                     //利用Dfs寻找路径

void Bfs()              //用Bfs找出最佳路径
{
    int head=0;
    int tail=0;
    q[tail++]=s;
    vis[0][0]=1;
    while(tail>head)
    {
        now=q[head++];

        //cout<<now.x<<" "<<now.y<<endl;
        //system("pause");

        if(mp[now.x][now.y]!='.' && mp[now.x][now.y]!='0')
        {
            mp[now.x][now.y]--;
            q[tail]=now;
            q[tail].before=head-1;
            q[tail].d++;
            tail++;
            continue;
        }

        if(now.x==n-1 && now.y==m-1)
        {
            printf("It takes %d seconds to reach the target position, let me show you the way.\n",now.d);
            print(head-1);
            return;
        }

        for(int i=0;i<4;i++)
        {
            int x=now.x+dx[i],y=now.y+dy[i];
            if(!vis[x][y] && judge(x,y))
            {
                q[tail].x=x;
                q[tail].y=y;
                q[tail].d=now.d+1;
                q[tail++].before=head-1;
                vis[x][y]=1;
            }
        }
    }
    printf("God please help our poor hero.\n");
}

int main()
{
	while(~scanf("%d%d",&n,&m))
	{
	    for(int i=0;i<n;i++)
        {
            scanf("%s",mp[i]);
            memset(vis[i],0,sizeof vis[i]);
        }
        //初始化
        cont=1;
        s.x=0;
        s.y=0;
        s.d=0;
        s.before=-1;

	    Bfs();
	    printf("FINISH\n");
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值