[USACO07OCT]障碍路线Obstacle Course

题目描述

Consider an N x N (1 <= N <= 100) square field composed of 1

by 1 tiles. Some of these tiles are impassible by cows and are marked with an 'x' in this 5 by 5 field that is challenging to navigate:

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

Bessie finds herself in one such field at location A and wants to move to location B in order to lick the salt block there. Slow, lumbering creatures like cows do not like to turn and, of course, may only move parallel to the edges of the square field. For a given field, determine the minimum number of ninety degree turns in any path from A to B. The path may begin and end with Bessie facing in any direction. Bessie knows she can get to the salt lick.

N*N(1<=N<=100)方格中,’x’表示不能行走的格子,’.’表示可以行走的格子。卡门很胖,故而不好转弯。现在要从A点走到B点,请问最少要转90度弯几次?

输入输出格式

输入格式:

 

第一行一个整数N,下面N行,每行N个字符,只出现字符:’.’,’x’,’A’,’B’,表示上面所说的矩阵格子,每个字符后有一个空格。

【数据规模】

2<=N<=100

 

输出格式:

 

一个整数:最少转弯次数。如果不能到达,输出-1。

 

输入输出样例

输入样例#1:
3
. x A
. . .
B x .
输出样例#1:
2

说明

【注释】

只可以上下左右四个方向行走,并且不能走出这些格子之外。开始和结束时的方向可以任意。

思路:BFS

代码实现:

 1 #include<cstdio>
 2 #include<iostream>
 3 using namespace std;
 4 int n,sx,sy,tx,ty;
 5 int nx,ny,np,ns,fx,fy,fp,fs;
 6 int cx[]={0,1,0,-1};
 7 int cy[]={1,0,-1,0};
 8 bool v[110][110][4],map[110][110];
 9 char ch;
10 int head,tail;
11 struct bfsw{int x,y,p,s;}q[40010];
12 int main(){
13     scanf("%d",&n);
14     for(int i=1;i<=n;i++)
15     for(int j=1;j<=n;j++){
16         cin>>ch;
17         if(ch=='x') map[i][j]=1;
18         if(ch=='A') sx=i,sy=j;
19         if(ch=='B') tx=i,ty=j;
20     }
21     for(int i=0;i<4;i++){
22         q[head++]=(bfsw){sx,sy,i,0};
23         v[sx][sy][i]=1;
24     }
25     while(head>tail){
26         nx=q[tail].x,ny=q[tail].y,np=q[tail].p,ns=q[tail++].s;
27         for(int i=0;i<2;i++){
28             fp=(np+1+2*i)%4;
29             if(!v[nx][ny][fp]){
30                 q[head++]=(bfsw){nx,ny,fp,ns+1};
31                 v[nx][ny][fp]=1;
32             }
33         }
34         fp=np,fx=nx+cx[fp],fy=ny+cy[fp];
35         while(fx>0&&fy>0&&fx<=n&&fy<=n&&!map[fx][fy]){
36             if(fx==tx&&fy==ty){
37                 printf("%d\n",ns);
38                 return 0;
39             }
40             if(!v[fx][fy][fp]) q[head++]=(bfsw){fx,fy,fp,ns};
41             fx+=cx[fp],fy+=cy[fp];
42         }
43     }
44     printf("-1\n");
45     return 0;
46 }

好歹是道犇站的题,给点面子吧。

题目来源:洛谷

posted @ 2017-03-01 20:17  J_william  阅读(438)  评论(0编辑  收藏  举报