贴一个bfs版的

wyh的迷宫

https://ac.nowcoder.com/acm/problem/15434

贴一个bfs版的#

刚开始只ac50%,因为把起点默认成(1,1)了orz
《论读题的重要性》

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
struct poin{
    int a ;
    int b ;
};
char mapn[ 505 ][ 505 ];
long long sum[ 505 ][ 505 ];
int x[ 4 ] = { 1 , -1 , 0 , 0  };
int y[ 4 ] = { 0 , 0 , 1 , -1  };

int n , m ;
int sx , sy ;

bool inmap( int a , int b ) //判断是否在地图内
{
    if( a > n || a < 1 ) return 0 ;
    if( b > m || b < 1 ) return 0 ;
    return 1 ;
}
int main()
{
    int t ;
    cin >> t ;
    while( t-- )
    {
        queue< poin >p; //用队列实现bfs
        bool flag = 0 ;
        memset(sum, -1 , sizeof sum  );
        cin >> n >> m ;
        for (int j = 1 ; j <= n ; j++ )
            for (int i = 1 ; i <= m ; i ++)
                {
                    cin >> mapn [ j ][ i ];
                    if( mapn[ j ][ i ] == 's' )
                        sx = j , sy = i ;//记录起始点坐标
                }

    sum[ sx ][ sy ] = 0 ;//把起始点放入队列(注意起点不是(1,1))
    p.push({ sx , sy });
    while( !p.empty() )
    {
            poin temp = p.front() ;
            p.pop();

        for ( int i = 0 ; i < 4 ; i ++ )
            {
                int tx = temp.a + x[ i ] ;
                int ty = temp.b + y[ i ] ;


                if( inmap( tx , ty  ) && sum[ tx ][ ty ] == -1 && mapn[ tx ][ ty ] != 'x' )
                    {
                        if( mapn[ tx ][ ty ] == 't' ) flag = 1 ;
                        sum[ tx ][ ty ] = sum[ temp.a ][ temp.b ] + 1 ;
                        p.push({ tx , ty });

                    }

            }
    }

            cout << ( flag ? "YES\n" : "NO\n");
    }
    return 0 ;
}



全部评论
大佬大佬bfs怎么写呀
点赞 回复 分享
发布于 2023-09-13 13:25 浙江

相关推荐

01-27 15:41
门头沟学院 Java
想躺平的菜鸡1枚:我项目比你难、学历比你好、还有SCI论文,投java都被拒一大片,现在基本上都要问点agent开发
软件开发投递记录
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务