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();
}
相关推荐
绝知此事几秒前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院8 分钟前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet1 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
LuminousCPP1 小时前
数据结构 - 线性表第四篇:C 语言通讯录优化升级全记录(踩坑 + 思考)
c语言·开发语言·数据结构·经验分享·笔记·学习
AI算法沐枫2 小时前
深度学习python代码处理科研测序数据
数据结构·人工智能·python·深度学习·决策树·机器学习·线性回归
m0_629494734 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户4 小时前
用队列实现栈
数据结构·算法
做人求其滴4 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
daad7774 小时前
记一组无人机IMU传感器数据
算法