AcWing 173. distance matrix (multi-source BFS)

Topic links: Click here

Here Insert Picture Description
Here Insert Picture Description

This problem can be seen as one more than the initial state of flood-fill problem. We matrix A A ineach of all as a starting point, all locations in the entire matrix can pass, for each location, in a case where any start point from the can, find the minimum number of steps reaches the desired position (i.e. distance the location of the nearest distance from the starting point).

In the initial state having a plurality of such problems equivalent, we only need to start before these BFS initial state queue full insertion . Depending on the nature of the BFS search step by step, the BFS process is equivalent to the starting point of each layer 1 is expanded first, and then expanded layer 2, layer 3, and so on. So when each location ( x , Y ) (X, y) for the first time when it is accessed, the equivalent distance of its recent extension to its starting point that, this time from the starting point to ( x , Y ) (X, y) the number of steps is experiencing the shortest distance B [ x ] [ Y ] B [x] [y] .

No space input matrix 01, the string read.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

#define x first 
#define y second

using namespace std;
typedef pair<int,int> PII;
const int N = 1010, M = N * N;

int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

int n, m;
char g[N][N];
int d[N][N];
PII q[M];

void bfs()
{
    int hh = 0, tt = -1;
    memset(d, -1, sizeof d);
    
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j)
            if(g[i][j] == '1')
                q[++tt] = {i, j}, d[i][j] = 0;
            
    while(hh <= tt)
    {
        PII t = q[hh++];
        for(int i = 0; i < 4; ++i)
        {
            int nx = t.x + dx[i], ny = t.y + dy[i];
            
            if(nx < 0 || nx >= n || ny < 0 || ny >= m)  continue;
            if(d[nx][ny] != -1) continue;
            
            q[++tt] = {nx, ny};
            d[nx][ny] = d[t.x][t.y] + 1;
        }
    }
}

int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; ++i)  scanf("%s", g[i]);
    
    bfs();
    
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < m; ++j)  printf("%d ", d[i][j]);
        puts("");
    }
    
    return 0;
}
Published 844 original articles · won praise 135 · Views 150,000 +

Guess you like

Origin blog.csdn.net/qq_42815188/article/details/105072801