dfs+bfs(三种路径问题)

题意:

给你一个h * w的迷宫,其中有一句话需要注意一下“Exactly one 'S' and one 'E' will be present in the maze, and they will always be located along one of the maze edges and never in a corner.”即始点‘S’和终点‘E’一定都与迷宫的边界相邻,这对做题很关键。然后问你沿着迷宫墙壁的左边走和沿着迷宫墙壁的右边走,各需多少步,然后最少需要多少步。

#include<iostream>
#include<queue>
using namespace std;
struct point
{
    int x,y;
    int step;
};
int flag[45][45];
char map[45][45];
int dir1[4][2]={{0,-1},{1,0},{0,1},{-1,0}};//zuo优先
int dir2[4][2]={{0,1},{1,0},{0,-1},{-1,0}};//you优先
int d1,d2;
int start[2];
int end[2];
int w,h;
void init()
{
    memset(flag,0,sizeof(flag));
    cin>>w>>h; 
    for(int i=0;i<h;i++)
    {
        cin>>map[i];
        for(int j=0;j<w;j++)
        {
            if(map[i][j]=='#')
            {
                flag[i][j]=1;
            }
            if(map[i][j]=='S')
            {
                start[0]=i;
                start[1]=j;
            }
            if(map[i][j]=='E')
            {
                end[0]=i;
                end[1]=j;
            }
        }
    }
    if(start[0]==0)
    {
        d1=1;
        d2=1;
    }
    else if(start[0]==h-1)
    {
        d1=3;
        d2=3;
    }
    else if(start[1]==w-1)
    {
        d1=2;
        d2=0;
    }
    else
    { 
        d1=0;
        d2=2;
    }
}
int dfs(int x,int y,int d,int dir[][2])
{
    int step ,temp, tempx,tempy;
    if(x==end[0]&&y==end[1])
        return 1;
    for(int i=0;i<4;i++)
    {
        temp=(d+i)%4;
        tempx=x+dir[temp][1];
        tempy=y+dir[temp][0];
        if(tempx>=0&&tempx<h&&tempy>=0&&tempy<w&&!flag[tempx][tempy])
            break;
    }
    step=dfs(tempx,tempy,(temp+3)%4,dir)+1;
    return step;
}


int bfs()
{
    memset(flag,0,sizeof(flag));
    queue<point> q;
    point p;
    p.x=start[0];
    p.y=start[1];
    p.step=1;
    flag[p.x][p.y]=1;
    q.push(p);
    while(!q.empty())
    {
        p=q.front();
        q.pop();
        if(p.x==end[0]&&p.y==end[1])
            return p.step;
        for(int i=0;i<4;i++)
        {
            point temp;
            temp.x=p.x+dir1[i][1];
            temp.y=p.y+dir1[i][0];
            if(temp.x>=0&&temp.x<h&&temp.y>=0&&temp.y<w&&map[temp.x][temp.y]!='#'&&!flag[temp.x][temp.y])
            {
                flag[temp.x][temp.y]=1;
                temp.step=p.step+1;
                q.push(temp);
            }
        }
    }
    return 0;
}




int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        init();
        cout<<dfs(start[0],start[1],d1,dir1)<<" ";
        cout<<dfs(start[0],start[1],d2,dir2)<<" ";
        cout<<bfs()<<endl;
    }
}
View Code

 

转载于:https://www.cnblogs.com/baoluqi/p/3745802.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值