矩阵距离——多源BFS

给定一个 N 行 M 列的 01 矩阵 A,Aij 与 Akl 之间的曼哈顿距离定义为:

dist(Aij,Akl)=|i−k|+|j−l|

输出一个 N 行 M 列的整数矩阵 B,其中:Bij=min1≤x≤N,1≤y≤M,Axy=1dist(Aij,Axy)

输入格式

第一行两个整数 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

解析:

将 "1" 点放入队列,再遍历即可。不过要注意输入的问题,要用字符数组输入。

复制代码
#include <bits/stdc++.h>
using namespace std;
#define int long long 
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
typedef pair<int,int> PII;
const int N=2e6+10;
char g[1010][1010];
int d[1010][1010];
bool vis[1010][1010];
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int n,m;
queue <PII> q;
void bfs()
{
    for (int i=0;i<n;i++)
    for (int j=0;j<m;j++)
    {
        if (g[i][j]=='1')
        {
            q.push({i,j});
            vis[i][j]=1;
        }
    }
    while (q.size())
    {
        int x=q.front().first;
        int y=q.front().second;
        q.pop();
        for (int i=0;i<4;i++)
        {
            int a=x+dx[i],b=y+dy[i];
            if (a>=0&&a<n&&b>=0&&b<m&&!vis[a][b])
            {
                d[a][b]=d[x][y]+1;
                q.push({a,b});
                vis[a][b]=1;
            }
        }
    }
}
signed main()
{
    ios;
    cin>>n>>m;
    for (int i=0;i<n;i++) cin>>g[i];
    bfs();
    for (int i=0;i<n;i++)
    {
        for (int j=0;j<m;j++) cout<<d[i][j]<<" ";
        cout<<endl;
    }
    return 0;
}
相关推荐
tryxr33 分钟前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_337 分钟前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia1 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z1 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark2 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd2 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
渡我白衣2 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9925 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法