题面描述
给定一个N行M列的01矩阵 A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为:
d
i
s
t
(
A
[
i
]
[
j
]
,
A
[
k
]
[
l
]
)
=
∣
i
−
k
∣
+
∣
j
−
l
∣
dist(A[i][j],A[k][l])=|i-k|+|j-l|
dist(A[i][j],A[k][l])=∣i−k∣+∣j−l∣
输出一个N行M列的整数矩阵B,其中:
B
[
i
]
[
j
]
=
m
i
n
(
1
≤
x
≤
N
,
1
≤
y
≤
M
,
A
[
x
]
[
y
]
=
1
)
d
i
s
t
(
A
[
i
]
[
j
]
,
A
[
x
]
[
y
]
)
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1){dist(A[i][j],A[x][y])}
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1)dist(A[i][j],A[x][y])
即求与每个位置曼哈顿距离最近的
1
1
1
1
≤
N
,
M
≤
1000
。
1≤N,M≤1000。
1≤N,M≤1000。
输入格式
第一行两个整数
N
N
N,
M
M
M。
接下来一个 N N N行 M M M列的 01 01 01矩阵,数字之间没有空格。
输出格式
一个
N
N
N行
M
M
M列的矩阵
B
B
B,相邻两个整数之间用一个空格隔开。
样例输入
3 4
0001
0011
0110
样例输出
3 2 1 0
2 1 0 0
1 0 0 1
思考
找出’ 1 1 1‘的位置,推进队列里,根据广搜流程,深度小的先搜索,就可以得出正解。
代码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<algorithm>
using namespace std;
const int N=1010;
const int dx[4]={0,0,-1,1};
const int dy[4]={-1,1,0,0};
struct node
{
int x,y;
node(){}
node(int x,int y):x(x),y(y){}
};
queue<node>q;
int d[N][N];
char s[N][N];
int n,m;
void bfs()
{
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
d[i][j]=-1;
}
for(int i=1;i<=n;i++)scanf("%s",s[i]+1);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(s[i][j]=='1')q.push(node(i,j)),d[i][j]=0;
}
while(!q.empty())
{
node now=q.front();q.pop();
for(int i=0;i<4;i++)
{
node nxt=now;
nxt.x+=dx[i];nxt.y+=dy[i];
if(nxt.x>=1&&nxt.x<=n&&nxt.y>=1&&nxt.y<=m)
{
if(d[nxt.x][nxt.y]==-1)
{
d[nxt.x][nxt.y]=d[now.x][now.y]+1;
q.push(nxt);
}
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
printf("%d ",d[i][j]);
}
puts("");
}
}
int main()
{
scanf("%d%d",&n,&m);
bfs();
return 0;
}