AcWing 3083矩阵距离

给定一个 n×m的 01 矩阵:

复制代码
a11 a12 ... a1m
...
an1 an2 ... anm

定义 aij��� 与 akl��� 之间的距离为 D(aij,akl)=|i−k|+|j−l|�(���,���)=|�−�|+|�−�|。

对于每个元素 aij���,请求出与它距离最近且值为 11 的元素 akl��� 和它的距离是多少。

另外注意,当元素 aij��� 本身就为 11 时,与它距离最近且值为 11 的元素就是它自己,距离为 00。

输入格式

第一行为两个整数,分别代表 n� 和 m�。

接下来的 n� 行,第 i� 行的第 j� 个字符代表 aij���。

输出格式

共 n� 行,第 i� 行的第 j� 个数字表示 aij��� 与其距离最近且值为 11 的元素的距离。

数据范围

1≤n,m≤10001≤�,�≤1000

输入样例:
复制代码
3 4
0001
0011
0110
输出样例:
复制代码
3 2 1 0
2 1 0 0
1 0 0 1

|------------------------------------------------------------------------------------------------------------------------------------------|
| 难度:简单 |
| 时/空限制:1s / 64MB |
| 总通过数:114 |
| 总尝试数:197 |
| 来源: BJWC2010 |

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>

using namespace std;

int n,m;
string temp;
vector<string>a;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
bool used[1002][1002];
int dis[1002][1002];

struct node{
	int x;
	int y;
};

queue<node>q;

int bfs()
{
	node start,next;
	while(!q.empty())
	{
		start=q.front();
		q.pop();
		for(int i=0;i<4;++i)
		{
			next.x=start.x+dir[i][0];
			next.y=start.y+dir[i][1];
			if((next.x<n&&next.x>=0)&&(next.y<m&&next.y>=0)&&(used[next.x][next.y]==false))
			{
				used[next.x][next.y]=true;
				dis[next.x][next.y]=dis[start.x][start.y]+1;
				q.push(next);
			}
		}
	}
}

void sol()
{
	cin>>n>>m;
	for(int i=0;i<n;++i)
	{
		cin>>temp;
		for(int j=0;j<m;++j)
		{
			if(temp[j]=='1'){
				q.push({i,j});
				used[i][j]=true;
			}
		}
		a.push_back(temp);
	}
	bfs();
	for(int i=0;i<n;++i)
	{
		for(int j=0;j<m;++j)
		{
			cout<<dis[i][j]<<' ';
		}
		cout<<endl;
	}

}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	sol();
}
相关推荐
sin_hielo2 分钟前
leetcode 3228
算法·leetcode
Chan1621 分钟前
Java 集合面试核心:ArrayList/LinkedList 底层数据结构,HashMap扩容机制详解
java·数据结构·spring boot·面试·intellij-idea
cheniie42 分钟前
【Janet】数据结构
数据结构·janet
xier_ran42 分钟前
力扣(LeetCode)100题:41.缺失的第一个正数
数据结构·算法·leetcode
Swift社区1 小时前
LeetCode 425 - 单词方块
算法·leetcode·职场和发展
weixin_307779132 小时前
软件演示环境动态扩展与成本优化:基于目标跟踪与计划扩展的AWS Auto Scaling策略
算法·云原生·云计算·aws
Carl_奕然2 小时前
【机器视觉】一文掌握常见图像增强算法。
人工智能·opencv·算法·计算机视觉
放羊郎2 小时前
人工智能算法优化YOLO的目标检测能力
人工智能·算法·yolo·视觉slam·建图
无敌最俊朗@3 小时前
友元的作用与边界
算法
Miraitowa_cheems3 小时前
LeetCode算法日记 - Day 104: 通配符匹配
linux·数据结构·算法·leetcode·深度优先·动态规划