Loading

P2689 东南西北

题目描述

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

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

输入输出格式

输入格式:

 

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

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

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

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

 

输出格式:

 

最少走多少步。

比较简单的搜索。

#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 0x3f3f3f3f;
int x1, y1, x2, y2,k;
char str[110];
int dfs(int x, int y, int st){
    if (x == x2&&y == y2)return 0;
    if (st+1 > k)return maxn;
    int a = x, b = y;
    if (str[st] == 'E'){ ++b; }
    else if (str[st] == 'S'){ --a; }
    else if (str[st] == 'W'){ --b; }
    else if (str[st] == 'N'){ ++a; }
    return min(dfs(x, y, st+1), dfs(a, b, st + 1) + 1);
}


int main(){
    cin >> x1 >> y1;
    cin >> x2 >> y2;
    cin >> k;
    for (int i = 1; i <= k; ++i)
        cin >> str[i];
    int ans=dfs(x1, y1, 1);
    if (ans == maxn)cout << -1 << endl;
    else cout << ans << endl;
}

 

posted @ 2019-02-12 15:18  青山新雨  阅读(317)  评论(0编辑  收藏  举报