[题解] Obstacle Course C++

题目

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值