矩阵距离
题意
一个01矩阵,需要输出每个元素为0的位置到最近元素为1的位置的曼哈顿距离。
思考
如果只是单纯的bfs会tle,所以这里采用的是多源bfs,与最短路中的超级源点相似,这里的起点是所有元素为1的位置,在一开始遍历01矩阵,将所有元素为1的位置加入队列,这样只需要一次bfs就可以计算整个矩阵。
#define first x
#define second y
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair <ll , ll> pii;
typedef priority_queue <ll ,vector<ll> ,greater<ll> > xiao;
typedef priority_queue <ll ,vector<ll> ,less<ll> > da;
const int N=1e5 + 10,inf = 0x3f3f3f3f,mod = 1e6 + 7;
const ull P = 131;
int mp[1005][1005];
int dist[1005][1005];
int n,m;
int dx[4] = {1 , -1 , 0 , 0};
int dy[4] = {0 , 0 , 1 , -1};
pii q[2000 * 2000];
void bfs()
{
memset(dist , -1 , sizeof dist);
int tt = 0,hh = 0;
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= m ; j++)
{
if(mp[i][j] == 1)
{
q[++tt] = {i , j};
dist[i][j] = 0;
}
}
}
hh++;
while(hh <= tt)
{
auto t = q[hh++];
for(int i = 0 ; i < 4 ; i++)
{
int nx = t.x + dx[i];
int ny = t.y + dy[i];
if(nx < 1 || nx > n || ny < 1 || ny > m)
{
continue;
}
if(dist[nx][ny] != -1)
{
continue;
}
dist[nx][ny] = dist[t.x][t.y] + 1;
q[++tt] = {nx , ny};
}
}
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i = 1 ; i <= n ; i++)
{
string s1;
cin>>s1;
for(int j = 0 ; j < s1.size() ; j++)
{
mp[i][j + 1] = (s1[j] - '0');
}
}
bfs();
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= m ; j++)
{
cout<<dist[i][j]<<" ";
}
cout<<"\n";
}
}