广搜之献给阿尔吉侬的花束

广搜之献给阿尔吉侬的花束_第1张图片

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int R,C,T,BeginX,BeginY,EndX,EndY;
char Map[205][205];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
int visited[205][205];
struct node
{
    int x,y,step;
    node(int xx=0,int yy=0,int ss=0):x(xx),y(yy),step(ss){}
};
queue  q;
void Bfs()
{
    q.push( node( BeginX, BeginY, 0) );
    visited[BeginX][BeginY] = 1;
    while( !q.empty() )
    {
        node now = q.front();
        q.pop();
        int NowX = now.x; int NowY = now.y; int NowStep = now.step;
        if( NowX == EndX && NowY == EndY )
        {
            cout << NowStep << endl;
            return;
        }
        for( int i = 0; i < 4; i++ )
        {
            int NextX = NowX + dx[i]; int NextY = NowY + dy[i];
            if( !visited[NextX][NextY] && Map[NextX][NextY] != '#' )
                {
                    q.push( node( NextX, NextY, NowStep + 1));
                    visited[NextX][NextY] = 1;
                }
        }
    }
    cout << "oop!" << endl;
}
int main()
{
    cin >> T;
    while( T-- )
    {
        cin >> R >> C;
        memset(Map, 0, sizeof(Map));
        memset(visited, 0, sizeof(visited));
        for( int i = 1; i <= R; i++ )
            for( int j = 1; j <= C; j++ )
            {
                cin >> Map[i][j];
                if( Map[i][j] == 'S' )
                {
                    BeginX = i;
                    BeginY = j;
                }
                if( Map[i][j] == 'E' )
                {
                    EndX = i;
                    EndY = j;
                }
            }
        for( int i = 0; i <= R+1; i++ )
            for( int j = 0; j <= C+1; j++ )
                if( i==0 || j==0 || i==R+1 || j==C+1 )
                    Map[i][j] = '#';
       while( !q.empty() )
        q.pop();
       Bfs();
    }
    return 0;
}

你可能感兴趣的:(广度优先搜索,搜索)