题目链接:http://poj.org/problem?id=3083
题目分析:
题目大意是在一个h行,w列的迷宫中,#表示不能行走,.表示可以行走,而S表示起始位置,E表示终止位置;
现从S位置出发,分别输出按照左优先、右优先的步数(及经过的点数),以及最短的步数。
规定只能向上下左右行走。
为了方便描述,用数字表示方向(可以参照样例理解):
1
0 (now) 2
3
1. 左优先: 按照0123的顺序访问;
2. 右优先: 按照2103的顺序访问;
3. 能够保证一定有解;
4. 保证起始位置只有一个出口。
优先搜索可以使用递归也可以非递归,都写了下。。
<span style="font-size:18px;">#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std ;
//
const int MAXM = 50 ;
int w, h, bx, by, nx, ny ;
int val[MAXM][MAXM] ;
int dir[4][2] = {{0,-1}, {-1,0}, {0,1}, {1,0}} ;
bool used[MAXM][MAXM] ;
queue< pair< pair<int, int>, int> > que ;
/*
1
0 2
3
*/
//left better
void searchLeft(int x, int y, int dd, int dep){
if( x == nx && y == ny ){
cout << dep << " " ;
return ;
}else for( int i = 0; i < 4; i++ ){
int tmp = (i+dd+3) % 4 ;
int dx = x + dir[tmp][0] ;
int dy = y + dir[tmp][1] ;
if( dx <= 0 || dx > h ) continue ;
if( dy <= 0 || dy > w ) continue ;
if( val[dx][dy] == 1 ) continue ;
if( dx == nx && dy == ny ){
cout << dep+1 << " " ;
return ;
}else{
searchLeft(dx, dy, tmp, dep+1) ;
break ;
}
}
return ;
}
//right better
void searchRight(){
int dep = 1, dd = 2 ;
int dx = bx, dy = by ;
while( 1 ){
if( dx == nx && dy == ny ) break ;
for( int i = 0; i > -4; i-- ){
int tmp = (i+dd+5) % 4 ;
int tx = dx + dir[tmp][0] ;
int ty = dy + dir[tmp][1] ;
if( tx <= 0 || tx > h ) continue ;
if( ty <= 0 || ty > w ) continue ;
if( val[tx][ty] == 1 ) continue ;
dx = tx, dy = ty ;
dd = tmp ; dep++ ;
break ;
}
}
cout << dep << " " ;
}
//best
void search(){
while( !que.empty() ) que.pop() ;
que.push( make_pair( make_pair(bx, by), 1) ) ;
while( !que.empty() ){
int x = que.front().first.first ;
int y = que.front().first.second ;
int dep = que.front().second ;
if( x == nx && y == ny ){
cout << dep << endl ;
break ;
}
que.pop() ;
for( int i = 0; i < 4; i++ ){
int dx = x + dir[i][0] ;
int dy = y + dir[i][1] ;
if( dx <= 0 || dx > h ) continue ;
if( dy <= 0 || dy > w ) continue ;
if( val[dx][dy] == 1 ) continue ;
val[dx][dy] = 1 ;
que.push( make_pair( make_pair(dx, dy), dep+1) ) ;
}
}
}
//
void deal(char ch, int i, int j){
switch( ch ){
case '.':
val[i][j] = 0 ;
break ;
case 'S':
val[i][j] = 0 ;
bx = i, by = j ;
break ;
case 'E':
val[i][j] = 0 ;
nx = i, ny = j ;
break ;
default:
break ;
}
}
//
int main(){
//freopen("1234.in","r",stdin) ;
int t ;
scanf("%d",&t) ;
while( t-- ){
char ch ;
scanf("%d%d\n",&w, &h) ;
memset(used, false, sizeof(used)) ;
for( int i = 1; i <= h; i++ ){
for( int j = 1; j <= w; j++ ){
val[i][j] = 1 ;
ch = getchar() ;
deal(ch, i, j) ;
}
ch = getchar() ;
}
searchLeft(bx, by, 0, 1) ;
searchRight() ;
search() ;
}
return 0 ;
}
</span>