Obstacle Course
题目
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
思路
bfs板子题,只是在拓展状态中要额外来个for枚举整行(列) ,并判断是否可行,由于第一次移动也算转弯了,所以最后答案要减一。
大麻 代码
#include<bits/stdc++.h>
using namespace std;
int n,ans=1e9,ex,ey;
int maze[1010][1010];
int dir[4][2]={{1,0},{0,-1},{-1,0},{0,1}};
bool vis[1010][1010];
bool in(int x,int y){
return x>=0 && x<n && y>=0 && y<n;
}
struct node{
int x;
int y;
int d;
node(int xx,int yy,int dd){
x=xx;
y=yy;
d=dd;
}
};
int bfs(int sx,int sy){
queue<node> q;
q.push(node(sx,sy,-1));
while(!q.empty()){
node now=q.front();
q.pop();
for(int i=0;i<4;i++){
for(int j=1;;j++){
int tx=now.x+dir[i][0]*j,ty=now.y+dir[i][1]*j;
if(!in(tx,ty) || maze[tx][ty]){
break;
}
if(vis[tx][ty]){
continue;
}
if(tx==ex && ty==ey){
return now.d+1;
}
if(!vis[tx][ty]){
vis[tx][ty]=1;
q.push(node(tx,ty,now.d+1));
}
}
}
}
return -1;
}
int main(){
int sx,sy;
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
char x;
cin>>x;
if(x=='x'){
maze[i][j]=1;
}
if(x=='A'){
maze[i][j]=1;
sx=i;
sy=j;
}
if(x=='B'){
ex=i;
ey=j;
}
}
}
cout<<bfs(sx,sy);
return 0;
}