BZOJ 1644: [Usaco2007 Oct]Obstacle Course 障碍训练课( BFS )

BFS... 我连水题都不会写了QAQ

-------------------------------------------------------------------------

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<queue>
 
#define rep( i , n ) for( int i = 0 ; i < n ; ++i )
#define clr( x , c ) memset( x , c , sizeof( x ) )
#define Rep( i , n ) for( int i = 1 ; i <= n ; ++i )
 
using namespace std;
 
const int maxn = 100 + 5;
const int inf = 0x3f3f3f3f;
const int dir[ 4 ][ 2 ] = { { 0 , 1 } , { 0 , -1 } , { 1 , 0 } , { -1 , 0 } };
const int turn[ 4 ][ 4 ] = { { 1 , 0 , 1 , 1 } , { 1 , 1 , 1 , 0 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 1 , 1 } };
const int face[ 4 ] = { 1 , 3 , 2 , 0 };
 
int d[ 4 ][ maxn ][ maxn ];
int G[ maxn ][ maxn ];
int goal[ 2 ] , start[ 2 ];
 
#define goal( x , y ) ( x == goal[ 0 ] && y == goal[ 1 ] )
 
struct Node {
int x , y , cnt , f;
};
 
queue< Node > Q;
 
void BFS() {
rep( i , 4 ) {
   d[ i ][ start[ 0 ] ][ start[ 1 ] ] = 0;
   
   Q.push( ( Node ) { start[ 0 ] , start[ 1 ] , 0 , i } );
   
}
while( ! Q.empty() ) {
Node o = Q.front();
Q.pop();
rep( i , 4 ) {
int x = o.x + dir[ i ][ 0 ] , y = o.y + dir[ i ][ 1 ];
if( ! G[ x ][ y ] ) continue;
int cnt = o.cnt + turn[ i ][ o.f ];
if( d[ face[ i ] ][ x ][ y ] > cnt ) {
d[ face[ i ] ][ x ][ y ] = cnt;
if( ! goal( x , y ) ) Q.push( ( Node ) { x , y , cnt , face[ i ] } );
}
}
}
}
 
int main() {
// freopen( "test.in" , "r" , stdin );
// freopen( "test.out" , "w" , stdout );
int n;
cin >> n;
clr( G , 0 );
Rep( i , n )
   Rep( j , n ) {
   
    char c = getchar();
   
    while( !( c == '.' || c== 'x' || c == 'A' || c == 'B' ) ) 
       c = getchar();
       
    switch( c ) {
   
    case '.' : G[ i ][ j ] = 1; break;
    case 'A' : G[ start[ 0 ] = i ][ start[ 1 ] = j ] = 1; break;
    case 'B' : G[ goal[ 0 ] = i ][ goal[ 1 ] = j ] = 1; break;
   
    default  : break;
   
    }
   
   }
clr( d , inf );
BFS();
int ans = inf;
rep( i , 4 ) 
   ans = min( ans , d[ i ][ goal[ 0 ] ][ goal[ 1 ] ] );
   
cout << ans << "\n";
return 0;
}

 

-------------------------------------------------------------------------

1644: [Usaco2007 Oct]Obstacle Course 障碍训练课

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 390  Solved: 199
[Submit][Status][Discuss]

Description

考虑一个 N x N (1 <= N <= 100)的有1个个方格组成的正方形牧场。有些方格是奶牛们不能踏上的,它们被标记为了'x'。例如下图:

. . B x .
. x x A .
. . . x .
. x . . .
. . x . .

贝茜发现自己恰好在点A处,她想去B处的盐块舔盐。缓慢而且笨拙的动物,比如奶牛,十分讨厌转弯。尽管如此,当然在必要的时候她们还是会转弯的。对于一个给定的牧场,请你计算从A到B最少的转弯次数。开始的时候,贝茜可以使面对任意一个方向。贝茜知道她一定可以到达。

Input

第 1行: 一个整数 N 行

2..N + 1: 行 i+1 有 N 个字符 ('.', 'x', 'A', 'B'),表示每个点的状态。

Output

行 1: 一个整数,最少的转弯次数。

Sample Input

3
.xA
...
Bx.

Sample Output

2

HINT

Source

 

posted @ 2015-06-06 20:51  JSZX11556  阅读(211)  评论(0编辑  收藏  举报