HDU-2102 A计划 BFS

版权声明:仅供研究,转载请注明出处。 https://blog.csdn.net/CSUstudent007/article/details/83867040
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
using namespace std;
 
char map[2][15][15], hash[2][15][15];
 
int sx, sy, ex, ey, sk, ek, S;
 
bool legal( char c )
{
    if( c== '.'|| c== 'S'|| c== '#'|| c== '*'|| c== 'P' )
    {
        return true;
    }
    return false;
}

void gchar( char &c )
{
    char t;
    while( t= getchar(), !legal( t ) ) ;
    c= t;
} 
 
struct Node
{
    int x, y, k, step;
}info;
 
int dis[4][2]= { 0, 1, 0, -1, 1, 0, -1, 0 };
 
bool BFS(  )
{
    memset( hash, 0, sizeof( hash ) ); // 不能单纯的判断某一点是否走过,而是该点是否有更优的解
    queue< Node >q;
    info.x= sx, info.y= sy, info.k= sk, info.step= 0;
    hash[sk][sx][sy]= 1;
    q.push( info );
    int cnt= 0;
    while( !q.empty() )
    {
        Node pos= q.front();
        q.pop();
        if( map[pos.k][pos.x][pos.y]== 'P'&& pos.step<= S )
        {
        //  printf( "step= %d\n", pos.step );
            return true;
        }
        for( int i= 0; i< 4; ++i )
        {
            int x= pos.x+ dis[i][0], y= pos.y+ dis[i][1], k= pos.k, step= pos.step;
            if( map[k][x][y]!= 0&& map[k][x][y]!= '*' )
            {
                if( map[k][x][y]!= '#'&& !hash[k][x][y]&& step< S )
                {// 其已走步数不能已经到达了S步
                    info.x= x, info.y= y, info.k= k, info.step= step+ 1;
                    hash[k][x][y]= 1;
                    q.push( info );
                }
                else if( map[k][x][y]== '#'&& map[ ( k+ 1 )% 2 ][x][y]!= '*'&& map[ ( k+ 1 )% 2 ][x][y]!= '#'&& !hash[ ( k+ 1 )% 2 ][x][y]&& step< S )
                {// 进行图之间的转化,但是不能够对应在下一个图中的墙
                    info.x= x, info.y= y, info.k= ( k+ 1 )% 2, info.step= step+ 1;
                    hash[ ( k+ 1 )% 2 ][x][y]= 1;
                    q.push( info );
                }
            }
        }
    }
    return false;
}
 
int main(  )
{
    int T;
    scanf( "%d", &T );
    while( T-- )
    {
        int N, M;
        scanf( "%d %d %d", &N, &M, &S );
        memset( map, 0, sizeof( map ) );
        for( int k= 0; k< 2; ++k )
        {
            for( int i= 1; i<= N; ++i )
            {
                for( int j= 1; j<= M; ++j )
                {
                    gchar( map[k][i][j] );
                    if( map[k][i][j]== 'S' )
                    {
                        sx= i, sy= j, sk= k;
                    }
                    if( map[k][i][j]== 'P' )
                    {
                        ex= i, ey= j, ek= k;
                    }
                }
            }
        }
        printf( BFS(  )? "YES\n": "NO\n" );
    }
}

猜你喜欢

转载自blog.csdn.net/CSUstudent007/article/details/83867040