P1746 离开中山路

原题链接

水!

#include 
#define x first
#define y second

using namespace std;
const int N = 1010;
char g[N][N];
int dist[N][N];
bool st[N][N];
typedef pair PII;
queue q;
int n, x1, sy, x2, y2;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};

void bfs()
{
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    dist[x1][sy] = 0;
    st[x1][sy] = true;
    q.push({x1, sy});
    
    while(q.size())
    {
        auto t = q.front();
        q.pop();
        if(t.x == x2 && t.y == y2)
        {
            cout << dist[x2][y2] << endl;
            return ;
        }
        for (int i = 0; i < 4; i ++ )
        {
            int a = t.x + dx[i], b = t.y + dy[i];
            if(a < 0 || a > n || b < 0 || b > n || st[a][b] || g[a][b] == '1')  continue;
            st[a][b] = true;
            dist[a][b] = dist[t.x][t.y] + 1;
            q.push({a, b});
        }
    }
    cout << -1 << endl;
}

int main()
{
    cin >> n;
    for (int i = 1; i <= n; i ++) 
		for (int j = 1; j <= n; j ++)
			cin >> g[i][j];
    cin >> x1 >> sy >> x2 >> y2;
    bfs();
    return 0;
}

你可能感兴趣的:(#,洛谷:疯狂A题训练——搜索篇,算法,c++,广度优先)