dfs
来源:互联网 发布:ubuntu 查看机器配置 编辑:程序博客网 时间:2024/06/05 11:47
题目描述
给出起点和终点的坐标及接下来T个时刻的风向(东南西北),每次可以选择顺风偏移1个单位或者停在原地。求到达终点的最少时间。
如果无法偏移至终点,输出“-1”。
输入输出格式
输入格式:第一行两个正整数x1,y1,表示小明所在位置。
第二行两个正整数x2,y2,表示小明想去的位置。
第三行一个整数T,表示T个时刻。
第四至第N+3行,每行一个字符,表示风向,即东南西北的英文单词的首字母。
输出格式:最少走多少步。
输入输出样例
输入样例#1:
1 12 25ENWWN
输出样例#1:
2
输入样例#2:
1 12 21W
输出样例#2:
-1
输入样例#3:
1 12 23WWW
输出样例#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;elsecout<<ans<<endl;return 0;}
阅读全文
0 0
- DFS
- DFS
- dfs
- dfs
- dfs
- dfs
- DFS
- DFS
- dfs
- DFS
- DFS
- DFS
- dfs
- DFS
- dfs
- dfs
- dfs
- dfs
- windbg-!address、!vadump、!vprot(读取内存状态)
- HDU
- 字体垂直居中的几种实现方法
- 博客地址已转移至http://blog.itttl.com
- 用shell脚本实现监控程序自动重启
- dfs
- Vue + ElementUI 手撸后台管理网站基本框架(一)创建项目
- Toast弹出信息
- 减少 per-cpu kthreads引发的系统抖动
- 大端和小端
- 低碳生活大奖赛
- 大数据之ETL设计详解
- Linux学习(十一):数据结构之栈和队列
- Spring CustomPropertyEditor