打卡信奥刷题(1058)用C++实现信奥 P1649 [USACO07OCT] Obstacle Course S

P1649 [USACO07OCT] Obstacle Course S

题目描述

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 N,下面 N N N 行,每行 N N N 个字符,只出现字符: . , x , A , B \verb!.!,\verb!x!,\verb!A!,\verb!B! .,x,A,B,表示上面所说的矩阵格子,每个字符后有一个空格。

输出格式

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

输入输出样例 #1

输入 #1

3
. x A
. . .
B x .

输出 #1

2

说明/提示

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

数据范围及约定

对于全部数据,保证 2 ≤ N ≤ 100 2\le N\le 100 2N100

C++实现

#include
#include
#include
using namespace std;
int n,x0,y0,xn,yn,ans=0x7fffffff/2,bj;char l;
int a[105][105];
int dx[4]={1,0,-1,0};
int dy[4]={0,-1,0,1};
void Read(){
scanf(“%d”,&n);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++) {
cin>>l;//读入字符的时候因为题目说了有空格,所以用cin而没用scanf
if(l==‘A’)x0=i,y0=j,a[i][j]=-1;//标记不能重复走
if(l==‘B’)xn=i,yn=j,a[i][j]=0;
if(l==‘x’)a[i][j]=-1;
}
}
void dfs(int x,int y,int t,int k){
if(k>=ans)return ;
if(xxn&&yyn){ans=min(ans,k);bj=1;return ;}//取ans最小并标记找到
for(int i=0;i<4;i++) {
int nx=dx[i]+x;int ny=dy[i]+y;//四个方向的走后点的新坐标
if(nx<=0||nx>n||ny<=0||ny>n)continue;//判界
if(!a[nx][ny]) {
a[nx][ny]=-1;//标记不能走
int f=0;
if(i!=t)f=1;if(t==-1)f=0;
dfs(nx,ny,i,k+f);
//下一个位置的坐标+方向+次数累加
a[nx][ny]=0;//回溯
}
}
}
int main()
{
Read();
dfs(x0,y0,-1,0);//下面是暴力dfs
if(bj)printf(“%d”,ans);
else printf(“-1”);
return 0;
}

在这里插入图片描述

后续

接下来我会不断用C++来实现信奥比赛中的算法题、GESP考级编程题实现、白名单赛事考题实现,记录日常的编程生活、比赛心得,感兴趣的请关注,我后续将继续分享相关内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值