POJ 2312 Battle City

本文介绍了一种使用优先队列实现的迷宫最短路径搜索算法。通过定义迷宫地图和障碍物,利用优先队列进行广度优先搜索(BFS),寻找从起点到终点的最短步数。文章提供了完整的C++代码实现,并解释了关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

优先队列的简单应用

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>
using namespace std;
struct type
{
    int x,y,step;
};
char s[350][350];
int m,n,dx[4]={-1,1,0,0},dy[4]={0,0,-1,1},ans,vis[350][350];
bool operator < (const type &a,const type &b) //记住用法
{
    return a.step>b.step;
}
bool judge(int x,int y)
{
    if(x<n&&x>=0&&y<m&&y>=0&&!vis[x][y]&&s[x][y]!='S'&&s[x][y]!='R')
        return true;
    return false;
}
int bfs(int x,int y)
{
    int i,j;
    type p;
    priority_queue<type> q;
    p.x=x;
    p.y=y;
    p.step=0;
    q.push(p);
    while(!q.empty())
    {
        p=q.top();
        q.pop();
        if(s[p.x][p.y]=='T')
            return p.step;
        for(i=0;i<4;i++)
        {
            int tx=p.x+dx[i],ty=p.y+dy[i];
            if(judge(tx,ty))
            {
                vis[tx][ty]=1;
                type tp;
                tp.x=tx;
                tp.y=ty;
                tp.step=p.step+1;
                if(s[tx][ty]=='B')
                    tp.step++;
                q.push(tp);
            }
        }
    }
    return -1;
}
int main()
{
    int i,j,sx,sy,ex,ey;
  //  freopen("test.txt", "r", stdin);
    while(scanf("%d%d",&n,&m)&&(n||m))
    {
        getchar();
        memset(vis,0,sizeof(vis));
        for(i=0;i<n;i++)
            gets(s[i]);
        for(i=0;i<n;i++)
            for(j=0;j<m;j++)         
                if(s[i][j]=='Y')
                {
                    sx=i;
                    sy=j;
                }           
        vis[sx][sy]=1;
        printf("%d\n",bfs(sx,sy));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值