bfs解法
走出迷宫
https://ac.nowcoder.com/acm/problem/14572
贴一份bfs解法
#include<iostream> #include<cstdio> #include<queue> #include<string> #include<cstring> #include<algorithm> using namespace std; #define debug(x); for( int i = 1 ; i <= n ; i ++) for( int k = 1 ; k <= m ; k ++) if(k!=m)cout<<x[i][k]<<" "; else cout<<x[i][k]<<"\n"; struct point{ long long a ; long long b ; }; long long m , n , sx , sy , ex , ey ; char mapn[ 505 ][ 505 ]; long long sum[ 505 ][ 505 ]; int x[ 4 ] = { 1 , -1 , 0 , 0 }; int y[ 4 ] = { 0 , 0 , -1 , 1 }; bool inmap( int a , int b ) { if( a < 1 || a > n ) return 0 ; if( b < 1 || b > m ) return 0 ; return 1 ; } int main() { while(cin >> n >> m) { memset( sum , -1 , sizeof sum ); queue< point >q; for( int i = 1 ; i <= n ; i ++ ) for( int k = 1 ; k <= m ; k++ ) { cin >> mapn[ i ][ k ] ; if( mapn[ i ][ k ] == 'S' ) sx = i , sy = k ; if( mapn[ i ][ k ] == 'E' ) ex = i , ey = k ; } sum[ sx ][ sy ] = 0 ; q.push({ sx , sy }); while( !q.empty() ) { point temp = q.front(); q.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 ] != '#') { sum[ tx ][ ty ] = sum[ temp.a ][ temp.b ] + 1; q.push({ tx , ty }); } } } if( sum[ ex ][ ey ] == -1 ) cout << "No\n"; else cout <<"Yes\n"; } return 0 ; }