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();
}
相关推荐
今天又在写代码9 小时前
数据结构v2
数据结构
加农炮手Jinx9 小时前
LeetCode 146. LRU Cache 题解
算法·leetcode·力扣
Rabitebla9 小时前
C++ 和 C 语言实现 Stack 对比
c语言·数据结构·c++·算法·排序算法
加农炮手Jinx9 小时前
LeetCode 128. Longest Consecutive Sequence 题解
算法·leetcode·力扣
旖-旎9 小时前
递归(汉诺塔问题)(1)
c++·学习·算法·leetcode·深度优先·递归
深邃-9 小时前
【数据结构与算法】-顺序表链表经典算法
java·c语言·数据结构·c++·算法·链表·html5
努力学习的小廉9 小时前
我爱学算法之—— 前缀和(上)
c++·算法
AC17809 小时前
深入浅出 PID 算法:原理、实现与应用实战
人工智能·算法·机器学习
就爱学编程9 小时前
惊叹数据结构之美,品味排序算法之妙:对计排、桶排的详细介绍
数据结构·算法·排序算法
啊我不会诶9 小时前
2025CCPC福建邀请赛补题
算法·深度优先