#hihocoder #1092 : Have Lunch Together

BFS

{
#ifdef DEBUG_
    ifstream fin("G:/1.txt");
#define cin fin
#endif
    int N,M;
    cin>>N>>M;
    FOR(i,0,N-1){
        cin>>map[i];
    }
    FOR(i,0,N-1)
        FOR(j,0,M-1){
            dis[i][j]=INF;
            if(map[i][j]=='H'){
                startX=i;
                startY=j;
                dis[i][j]=0;
            }
        }
        q.push(make_pair(startX,startY));
        inq[startX][startY]=true;
        pair<int,int>   tmp;
        while (!q.empty())
        {
            tmp=q.front();
            q.pop();
            FOR(i,0,3){//遍历周围四个位置
                int newx=tmp.first+pos[i][0],newy=tmp.second+pos[i][1];
                if(newx>=0&&newx=0&&newyif(map[newx][newy]!='#'&&map[newx][newy]!='P'){
                        dis[newx][newy]=min(dis[newx][newy],dis[tmp.first][tmp.second]+1);
                        if(map[newx][newy]=='S')
                            inq[newx][newy]=true;
                        else if(!inq[newx][newy])
                            q.push(make_pair(newx,newy));
                            inq[newx][newy]=true;
                    }
                }
            }

        }
    int ans =INF;
    FOR(i,0,N-2){
        FOR(j,0,M-2){
            if(map[i][j]=='S'){
                if(map[i+1][j]=='S')
                    ans=min(ans,dis[i][j]+dis[i+1][j]);

                if (map[i][j+1]=='S' )
                    ans=min(ans,dis[i][j]+dis[i][j+1]);
            }
        }
    }
    if(ans==INF)
        cout<<"Hi and Ho will not have lunch."<else
        cout<return 0;
}

你可能感兴趣的:(BFS,bfs)