HDU 1072 Nightmare BFS

这道题用BFS应该简单的,处理好时间的重置就行,直接上代码。
 
 
#include <iostream>
#include <cstdio>
#include <string.h>
#include <queue>
using namespace std;
struct node{
    int x,y,step,time;
}start;
int n,m;
int map[10][10];
int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};  //控制方向
void bfs(){
    queue<node>q;
    node q1,q2;
    q.push(start);
    while(!q.empty()){
        q1=q.front();
        q.pop();
        for(int i=0;i<4;i++){
            q2.x=q1.x+to[i][0];
            q2.y=q1.y+to[i][1];
            q2.step=q1.step+1;
            q2.time=q1.time-1;
            if(q2.x>=0&&q2.x<n&&q2.y>=0&&q2.y<m&&map[q2.x][q2.y]!=0&&q2.time>0){
                if(map[q2.x][q2.y]==3){         //终点
                    cout<<q2.step<<endl;
                    return;
                }
                if(map[q2.x][q2.y]==4){         //重置时间
                    q2.time=6;
                    map[q2.x][q2.y]=0;
                }
                q.push(q2);
                //cout<<q2.x<<" "<<q2.y<<endl;
            }
        }
    }
    cout<<-1<<endl;

}

int main()
{
    int t;
    cin>>t;
    while(t--){
        memset(map,0,sizeof(map));
        cin>>n>>m;
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                cin>>map[i][j];
                if(map[i][j]==2){
                    start.x=i;
                    start.y=j;
                    start.step=0;
                    start.time=6;
                }
            }
        }
        //cout<<start.x<<" "<<start.y<<endl;
        bfs();

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38071217/article/details/76851181