dfs

题目描述

给出起点和终点的坐标及接下来T个时刻的风向(东南西北),每次可以选择顺风偏移1个单位或者停在原地。求到达终点的最少时间。

如果无法偏移至终点,输出“-1”。

输入输出格式

输入格式:

第一行两个正整数x1,y1,表示小明所在位置。

第二行两个正整数x2,y2,表示小明想去的位置。

第三行一个整数T,表示T个时刻。

第四至第N+3行,每行一个字符,表示风向,即东南西北的英文单词的首字母。

输出格式:

最少走多少步。

输入输出样例

输入样例#1:
1 1
2 2
5
E
N
W
W
N
输出样例#1:
2
输入样例#2:
1 1
2 2
1
W
输出样例#2:
-1
输入样例#3:
1 1
2 2
3
W
W
W
输出样例#3:
-1

说明

样例1:向东走一步,向南走一步。

样例2、3:无法到达。

1<=T<=50

东:East

南:South

西:West

北:North


















#include<iostream>
#include<algorithm>
using namespace std;
char t;
int n,ans=999999,nextt[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
int w[1000],book[1000][1000];
int startx,starty,endx,endy;

int get(char c)
{
    if(c=='N')
    {
        return 0;
    }
    if(c=='E')
    {
        return 1;
    }
    if(c=='S')
    {
        return 2;
    }
    if(c=='W')
    {
        return 3;
    }
}

bool limit(int x,int y)
{
	return x>=1&&x<=n&&y>=1&&y<=n&&book[x][y]==0;
}

void dfs(int x,int y,int now,int step) //step tiem  now buzhou
{
	if(x==endx&&y==endy)
	{
		ans=min(ans,now);
		return ;
	}
	if(step==n+1)
		return ;
	int tx,ty,d;
	d=w[step];
	
	tx=x+nextt[d][0];
	ty=y+nextt[d][1];
	if(limit(tx,ty))
	{
		book[tx][ty]=1; //标记来过
		dfs(tx,ty,now+1,step+1);  //时间加一 并且步数加一
		book[tx][ty]=0;//回溯
	}
	dfs(x,y,now,step+1);  //步数不加 时间仍然继续
	return ;
}
		
int main()
{
	cin>>startx>>starty>>endx>>endy;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>t;
		w[i]=get(t);
	}

	dfs(startx,starty,0,1);
	if(ans==999999)
		cout<<-1<<endl;
	else
		cout<<ans<<endl;
	return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值