Loading

AcWing 1470. 水桶传递队列

题目链接

https://www.acwing.com/problem/content/1472/

题目思路

没有技巧,全是感情,bfs经典模板题

题目代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
typedef pair<int, int> PII;
const int N = 20;
char g[N][N];
int dist[N][N];
bool st[N][N];

int bfs(int x, int y)
{
    memset(dist, -1, sizeof dist);
    queue<PII> q;
    q.push({x, y});
    dist[x][y] = 0;
    st[x][y] = true;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int dx[x] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
        for(int i = 0; i < 4; i ++ )
        {
            int a = t.first + dx[i], b = t.second + dy[i];
            if(a >= 0 && a < 10 && b >= 0 && b < 10 && !st[a][b] && g[a][b] != 'R')
            {
                dist[a][b] = dist[t.first][t.second] + 1;
                st[a][b] = true;
                q.push({a, b});
                if(g[a][b] == 'L') return dist[a][b] - 1;
            }
        }
    }
}

int main()
{
    int x, y;
    for(int i = 0; i < 10; i ++ )
    {
        for(int j = 0; j < 10; j ++ )
        {
            cin >> g[i][j];
            if(g[i][j] == 'B')
            {
                x = i, y = j;
            }
        }
    }
    cout << bfs(x, y) << endl;
    return 0;
}
posted @ 2022-03-29 20:01  vacilie  阅读(41)  评论(0)    收藏  举报