BFS(需要标记多个变量)

此题涉及颜色跟方向,标记数组可以开城四维分别表示坐标,方向和颜色。刚开始思路比较乱,做完之后要三思啊。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=30;
struct node
{
    int x,y;
    int drection;
    int color;
    int time;
};
char grid[maxn][maxn];
int dx[]= {-1,0,1,0};
int dy[]= {0,1,0,-1};
int vis[maxn][maxn][5][5];
int N,M;
int sx,sy,ex,ey;
string Color[]= {"green","black","red","blue","white"};

bool BFS()
{
    queue<node> q;
    node a,b;
    a.x=sx,a.y=sy,a.drection=0,a.color=0;
    a.time=0;
    q.push(a);
    while(!q.empty())
    {
        a=q.front();
        q.pop();
        if(a.x==ex&&a.y==ey&&a.color==0)
        {
            printf("minimum time = %d sec\n",a.time);
            return true;
        }
        b.time=a.time+1;

        b.x=a.x+dx[a.drection],b.y=a.y+dy[a.drection];
        b.drection=a.drection;
        b.color=(a.color+1)%5;
        if(b.x>=1&&b.x<=N&&b.y>=1&&b.y<=M&&grid[b.x][b.y]!='#'&&!vis[b.x][b.y][b.drection][b.color])
        {
            q.push(b);
            vis[b.x][b.y][b.drection][b.color]=1;
        }
        b.x=a.x,b.y=a.y;
        b.drection=(a.drection+3)%4;
        b.color=a.color;
        if(!vis[b.x][b.y][b.drection][b.color])
        {
            q.push(b);
            vis[b.x][b.y][b.drection][b.color]=1;
        }
        b.drection=(a.drection+1)%4;
        if(!vis[b.x][b.y][b.drection][b.color])
        {
            q.push(b);
            vis[b.x][b.y][b.drection][b.color]=1;
        }
    }
    return false;
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
    #endif
    int cas=1;
    while(cin>>N>>M,N+M)
    {
        if(cas!=1)printf("\n");
        for(int i=1; i<=N; i++)
        {
            for(int j=1; j<=M; j++)
            {
                cin>>grid[i][j];
                if(grid[i][j]=='S')
                {
                    sx=i,sy=j;
                }
                if(grid[i][j]=='T')
                {
                    ex=i,ey=j;
                }
            }

        }
        memset(vis,0,sizeof(vis));
        vis[sx][sy][0][0]=1;
        printf("Case #%d\n",cas++);
        if(!BFS())cout<<"destination not reachable"<<endl;
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值