Codeforces Round #442 (Div. 2) 877 D. Olya and Energy Drinks BFS

来源:互联网 发布:超级直播软件apk 编辑:程序博客网 时间:2024/05/29 04:04

题目链接: D. Olya and Energy Drinks

题目大意

一个n*m的迷宫, 0m,n103, 给定一个起点和一个终点, 每秒可以向上下左右中的某一个方向最多前进k步, 求起点到终点最少需要花费的时间

思路

最普通的BFS, 但复杂度O(nmk)=109, 会超时, 但是只要遇到终点立即退出(输出答案然后return), 就能过

代码

GNU C++14 Accepted 1747 ms 13600 KB

#include <iostream>#include <algorithm>#include <cstring>#include <cstdio>#include <queue>using namespace std;const int maxn = 1e3 + 10;int n, m, k, d[maxn][maxn];int x_1, x_2, y_1, y_2;int dx[] = {0, 0, 1, -1};int dy[] = {1, -1, 0, 0};char s[maxn][maxn];typedef pair<int, int> P;int main(){    scanf("%d%d%d", &n, &m, &k);    for (int i = 0; i < n; ++i) scanf("%s", s[i]);    scanf("%d%d%d%d", &x_1, &y_1, &x_2, &y_2);    if(x_1 == x_2 && y_1 == y_2)    {        cout << 0 << endl;        return 0;    }    --x_1, --x_2, --y_1, --y_2;    memset(d, -1, sizeof(d));    d[x_1][y_1] = 0;    queue<P> que;    que.push(P(x_1, y_1));    while (!que.empty())    {        P now = que.front(); que.pop();        for (int i = 0; i < 4; ++i)        {            for (int a = 1; a <= k; ++a)            {                int nx = now.first + dx[i] * a;                int ny = now.second + dy[i] * a;                if (0 <= nx && nx < n && 0 <= ny && ny < m && d[nx][ny] == -1 && s[nx][ny] == '.')                {                    d[nx][ny] = d[now.first][now.second] + 1;                    que.push(P(nx, ny));                    if (nx == x_2 && ny == y_2)                    {                        cout << d[x_2][y_2] << endl;                        return 0;                    }                }                else if (nx < 0 || nx >= n || ny < 0 || ny >= m || s[nx][ny] == '#') break;            }        }    }    cout << -1 << endl;    return 0;}
阅读全文
0 0
原创粉丝点击