hdu 1242 Rescue(bfs)

本文提供了一种解决迷宫问题的方法,通过C语言实现了一个寻找从起点到终点路径的算法。该算法使用了广度优先搜索策略,并考虑了特殊条件如‘x’标记的格子会增加额外的时间成本。

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1242

#include <stdio.h>
#include <string.h>
char map[201][201];
int book[201][201];
int next[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
struct
{
    int x;
    int y;
    int step;//保存用时
} node[40404];

int main()
{
    int i,j,n,m,tx,ty,head,tail,k;
    int endx,endy,flag;
    while(scanf(" %d %d",&n,&m) != EOF)
    {
        flag = 0;
        for(i = 1; i <= n; ++i)
            for(j = 1; j <= m; ++j)
            {
                scanf(" %c",&map[i][j]);
                if(map[i][j] == 'r')
                {
                    tx = i;
                    ty = j;
                }
                if(map[i][j] == 'a')
                {
                    endx = i;
                    endy = j;
                }
            }
        memset(book,0,sizeof(book));
        head = tail = 1;
        node[0].step = node[1].step = 0;
        book[tx][ty] = 1;
        node[tail].x = tx;
        node[tail].y = ty;
        tail++;
        while(head < tail)
        {
            for(k = 0; k < 4; ++k)
            {
                tx = node[head].x + next[k][0];
                ty = node[head].y + next[k][1];
                if(tx < 1 || ty < 1 || tx > n || ty > m)
                    continue;
                if(map[tx][ty] != '#' && book[tx][ty] == 0)
                {
                    node[tail].step = 0;
                    book[tx][ty] = 1;
                    node[tail].x = tx;
                    node[tail].y = ty;
                    node[tail].step = node[head].step+1;//下一步的时间等于上一步的时间加1

                    if(map[tx][ty] == 'x')//杀死一个守卫,增加一个时间
                        node[tail].step += 1;

                    tail++;
                }
                if((tx == endx) && (ty == endy))
                {
                    flag = 1;
                    break;
                }
            }
            if(flag == 1)
                break;
            head++;
        }
        if(flag == 1)
            printf("%d\n",node[tail-1].step);
        else
            printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值