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

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

BFS哟~看到有大佬代码极短,涨知识了~对于只需要计算最短路长度的问题,队列存储x*m+y就可以了~~不用新开结构体~记笔记记笔记~(zz一样有种发现新大陆的感觉,大概只有全世界只有我不知道这样处理了orz,2333333)

#include<iostream> //bfs
#include<algorithm>
#include<queue>
#include<stdio.h>
using namespace std;
char mize[1005][1005];
int dis[1005][1005];
int cnt = 0,m,n,k;
int sx, sy, ex, ey;
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int bfs()
{
    if (ex == sx&&ey == sy) return 0;
    queue<int>q;
    int a = sx*m + sy;
    q.push(a);
    memset(dis, -1, sizeof(dis));
    dis[sx][sy] = 0;
    while (!q.empty())
    {
        a = q.front();
        q.pop();
        int x = a / m;
        int y = a%m;
        for (int i = 0; i < 4; i++)
        {
            for (int j = 1; j <= k; j++)
            {
                int nx = x + dx[i] * j;
                int ny = y + dy[i] * j;
                if (mize[nx][ny] == '#' || nx >= n || nx < 0 || ny < 0||ny>=m) break;
                if (dis[nx][ny] <0)
                    {
                        dis[nx][ny] = dis[x][y] + 1;
                        if (nx == ex&&ny == ey) return dis[nx][ny];
                        q.push(nx*m + ny);
                    }
            }
        }

    }
    return -1;
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> n >> m >> k;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> mize[i][j];
    cin >> sx >> sy >> ex >> ey;
    sx--; sy--; ex--; ey--;
    cout << bfs() << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/Egoist-/p/7732676.html