迷宫
2. 思路
dfs或者bfs搜索,但题目要求最短路径,此时用广搜bfs. 好了不码了,实际上就是罗勇军老师《蓝桥杯》的原代码,只是自己理解了而已。 祝我明天比赛顺利!!(拿奖!!)
3. 代码展示
#include <bits/stdc++.h>
#include <iostream>
#include <string.h>
#include <stack>
typedef long long ll;
const int N= 1005 ;
using namespace std;
char a[ 31 ] [ 51 ] ;
char k[ 4 ] = { 'D' , 'L' , 'R' , 'U' } ;
bool vis[ 30 ] [ 50 ] ;
int dir[ 4 ] [ 2 ] = { { 1 , 0 } , { 0 , - 1 } , { 0 , 1 } , { - 1 , 0 } } ;
char pre[ 31 ] [ 51 ] ;
struct Node{
int x;
int y;
} ;
void print ( int x, int y) {
if ( x== 0 && y== 0 ) return ;
if ( pre[ x] [ y] == 'D' ) print ( x- 1 , y) ;
if ( pre[ x] [ y] == 'U' ) print ( x+ 1 , y) ;
if ( pre[ x] [ y] == 'L' ) print ( x, y+ 1 ) ;
if ( pre[ x] [ y] == 'R' ) print ( x, y- 1 ) ;
cout<< pre[ x] [ y] ;
}
void bfs ( ) {
queue< Node> q;
Node nex, now;
now. x= 0 ; now. y= 0 ;
q. push ( now) ;
vis[ 0 ] [ 0 ] = 1 ;
while ( ! q. empty ( ) ) {
now = q. front ( ) ;
q. pop ( ) ;
if ( now. x== 29 && now. y== 49 ) {
print ( 29 , 49 ) ;
return ;
}
for ( int i= 0 ; i< 4 ; ++ i) {
nex. x = now. x + dir[ i] [ 0 ] ;
nex. y = now. y + dir[ i] [ 1 ] ;
if ( nex. x> 29 || nex. x< 0 || nex. y< 0 || nex. y> 49 ) continue ;
if ( vis[ nex. x] [ nex. y] == 1 || a[ nex. x] [ nex. y] == '1' ) continue ;
vis[ nex. x] [ nex. y] = 1 ;
q. push ( nex) ;
pre[ nex. x] [ nex. y] = k[ i] ;
}
}
}
int main ( ) {
for ( int i= 0 ; i< 30 ; ++ i) cin>> a[ i] ;
bfs ( ) ;
return 0 ;
}