矩陣距離(多源BFS)
阿新 • • 發佈:2021-02-03
技術標籤:資料結構
題目描述
給定一個N行M列的01矩陣A,A[i][j] 與 A[k][l] 之間的曼哈頓距離定義為:
dist(A[i][j],A[k][l])=|i−k|+|j−l|
輸出一個N行M列的整數矩陣B,其中:
B[i][j]=min1≤x≤N,1≤y≤M,A[x][y]=1dist(A[i][j],A[x][y])
輸入格式
第一行兩個整數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
思路:本題是求0的位置距離所有1的最短的曼哈頓距離。
求一個點到多個起點的最短距離,可以給所有起點加一個虛擬點(與起點距離為0),這樣就把題目轉化成求這個點到虛擬點的最短距離。
本題僅需把所有1節點入隊,並把距離置為0,轉化成跑單源bfs。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
const ll INF=0x3f3f3f3f;
ll n,m;
struct node{
ll x,y;
};
char mp[1005][1005];
ll dis[1005][1005];
ll dx[4]={-1,1,0,0};
ll dy[4]={0,0,-1,1};
queue<node> q;
void dfs()
{
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
if(mp[i][j]=='1')
{
dis[i][j]=0;
q.push({i,j});
}
}
while(!q.empty())
{
node temp=q.front();
q.pop( );
for(int i=0;i<4;i++)
{
ll x=temp.x+dx[i];
ll y=temp.y+dy[i];
if(x<0||y<0||x>=n||y>=m) continue;
if(dis[x][y]!=-1) continue;
dis[x][y]=dis[temp.x][temp.y]+1;
q.push({x,y});
}
}
}
int main()
{
memset(dis,-1,sizeof(dis));
cin>>n>>m;
for(int i=0;i<n;i++) cin>>mp[i];
dfs();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cout<<dis[i][j]<<" ";
cout<<endl;
}
return 0;
}