其他分享
首页 > 其他分享> > P1746 离开中山路

P1746 离开中山路

作者:互联网

题目链接

https://www.luogu.com.cn/problem/P1746

题目思路

今天全是bfs题,这道题记住只有0可以走

题目代码

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

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

int bfs(int x1, int y1, int x2, int y2)
{
    memset(dist, -1, sizeof dist);
    memset(st, false, sizeof st);
    queue<PII> q;
    q.push({x1, y1});
    dist[x1][y1] = 0;
    st[x1][y1] = true;
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        int dx[4] = {-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 >= 1 && a <= n && b >= 1 && b <= n && !st[a][b] && g[a][b] == 0)
            {
                dist[a][b] = dist[t.first][t.second] + 1;
                if(a == x2 && b == y2) return dist[a][b];
                q.push({a, b});
                st[a][b] = true;
            }
        }
    }
}

int main()
{
    cin >> n;
    for(int i = 1; i <= n; i ++ )
    {
        string a;
        cin >> a;
        for(int j = 1; j <= n; j ++ )
            g[i][j] = a[j - 1] - '0';
    }

    int x1, y1, x2, y2;
    cin >> x1 >> y1 >> x2 >> y2;
    cout << bfs(x1, y1, x2, y2) << endl;
    return 0;
}

标签:include,dist,int,P1746,中山路,st,离开,y1,x1
来源: https://www.cnblogs.com/vacilie/p/16063894.html