173. 矩阵距离(多源bfs)

给定一个 N 行 M 列的 01 矩阵 A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为:

dist(A[i][j],A[k][l])=|i−k|+|j−l|
输出一个 N 行 M 列的整数矩阵 B,其中:

B[i][j]=min1≤x≤N,1≤y≤M,A[x][y]=1dist(A[i][j],A[x][y])
输入格式
第一行两个整数 N,M。

接下来一个 N 行 M 列的 01 矩阵,数字之间没有空格。

输出格式
一个 N 行 M 列的矩阵 B,相邻两个整数之间用一个空格隔开。

数据范围
1≤N,M≤1000

输入样例:
3 4
0001
0011
0110
输出样例:
3 2 1 0
2 1 0 0
1 0 0 1
#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
const int N = 1e3 + 10;
typedef pair<int,int>PII;
int g[N][N],vis[N][N],dist[N][N];
struct Node{
    int x,y;
    int d;
}node[N];
queue<PII>q;
int n,m;
void bfs(){
    for(int i = 0;i < n;i ++){
        for(int j = 0;j < m;j ++){
            if(g[i][j] == 1){
                vis[i][j] = true;
                dist[i][j] = 0;
                q.push({i,j});
            }
        }
    }
    int dx[4] = {0,1,0,-1},dy[4] = {-1,0,1,0};
    while(!q.empty()){
        PII t = q.front();
        q.pop();
        for(int k = 0;k < 4;k ++){
            int a = t.x + dx[k],b = t.y + dy[k];
            if(a < 0 || a >= n || b < 0 || b >= m || vis[a][b])continue;
            vis[a][b] = true;
            dist[a][b] = dist[t.x][t.y] + 1;
            q.push({a,b});
        }
    }
    for(int i = 0;i < n;i ++){
        cout<<dist[i][0];
        for(int j = 1;j < m;j ++){
            cout<<" "<<dist[i][j];
        }
        cout<<endl;
    }
}
int main(){
    cin>>n>>m;
    char x;
    for(int i = 0;i < n;i ++){
        for(int j = 0;j < m;j ++)cin>>x,g[i][j] = x - '0';
    }
    bfs();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值