大白鼠上的简单BFS。。。
今天简直累爱,本想做一道简单题放松心情的,结果调了我一早上= =,最后才发现是路径和记录的对不上导致错误,真是坑QAQ,不爱了不爱了。。。
就是每个节点记录三个信息,坐标,朝向,颜色。然后扩展节点的时候,要么前进,要么转向,然后最后第一次到达终点时的花费一定是最小的,BFS嘛。
代码如下:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std ;
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define clear( A , X ) memset ( A , X , sizeof A )
const int maxF = 4 ;
const int maxC = 5 ;
const int maxN = 25 ;
const int maxH = 1000000 ;
struct Queue {
int x , y ;
int f ;//dir 0 , 1 , 2 , 3
// n , w , s , e
int c ;//color 0 , 1 , 2 , 3 , 4
int t ;//cost time
Queue () {}
Queue ( int X , int Y , int F , int C , int T ) : x(X) , y(Y) , f(F) , c(C) , t(T) {}
} ;
Queue Q[maxH] ;
int head , tail ;
int vis[maxN][maxN][maxF][maxC] ;
int path[4][2] = {
{ -1 , 0 } ,//n
{ 0 , -1 } ,//w
{ 1 , 0 } ,//s
{ 0 , 1 } ,//e
} ;
char G[maxN][maxN] ;
int n , m ;
void BFS () {
int ans = 0 ;
while ( head != tail ) {
Queue u = Q[head ++] ;
if ( G[u.x][u.y] == 'T' && !u.c ) {
printf ( "minimum time = %d sec\n" , u.t ) ;
return ;
}
REP ( f , maxF ) {
if ( abs ( u.f - f ) == 2 ) continue ;
if ( u.f == f ) {
int x = u.x + path[f][0] ;
int y = u.y + path[f][1] ;
int c = u.c + 1 ;
if ( c >= 5 ) c -= 5 ;
if ( x >= 0 && y >= 0 && x < n && y < m && G[x][y] != '#' && !vis[x][y][f][c] ) {
vis[x][y][f][c] = 1 ;
Q[tail ++] = Queue ( x , y , f , c , u.t + 1 ) ;
}
}
else if ( !vis[u.x][u.y][f][u.c] ) {
vis[u.x][u.y][f][u.c] = 1 ;
Q[tail ++] = Queue ( u.x , u.y , f , u.c , u.t + 1 ) ;
}
}
}
printf ( "destination not reachable\n" ) ;
}
void Work () {
int cas = 0 ;
while ( ~scanf ( "%d%d" , &n , &m ) && ( n || m ) ) {
if ( cas ) printf ( "\n" ) ;
printf ( "Case #%d\n" , ++ cas ) ;
head = tail = 0 ;
clear ( vis , 0 ) ;
REP ( i , n ) scanf ( "%s" , G[i] ) ;
REP ( i , n ) REP ( j , m ) if ( G[i][j] == 'S' ) {
vis[i][j][0][0] = 1 ;
Q[tail ++] = Queue ( i , j , 0 , 0 , 0 ) ;
break ;
}
BFS () ;
}
}
int main () {
Work () ;
return 0 ;
}