【图论最短路】【CQBZOJ 1633】【图论专项赛】位图

d(p1,p2)=|i1i2|+|j1j2| $d(p1,p2)=|i1-i2|+|j1-j2|$

3 4
0001
0011
0110

3 2 1 0
2 1 0 0
1 0 0 1

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;

#define MAXN 182
#define MAXM 182
#define INF 0x3f3f3f3f
typedef long long int LL;

int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
struct point
{
int x,y;
point(){}
point(int a,int b):x(a),y(b){}
};

int M,N;
bool G[MAXM+10][MAXN+10];

queue<point>que;
int dist[MAXM+10][MAXN+10];
bool vis[MAXM+10][MAXN+10];
void Spfa()
{
memset(dist,0x3f,sizeof(dist));
memset(vis,0,sizeof(vis));
while(!que.empty())que.pop();

for(int i=1;i<=M;++i)
for(int j=1;j<=N;++j)
if(G[i][j])
{
dist[i][j]=0;
que.push(point(i,j));
vis[i][j]=1;
}

point now;
int nx,ny;
while(!que.empty())
{
now=que.front();que.pop();
vis[now.x][now.y]=0;

for(int i=0;i<4;++i)
{
nx=now.x+dir[i][0],ny=now.y+dir[i][1];

if(nx<1||ny<1||nx>M||ny>N)continue;

if(dist[nx][ny]>dist[now.x][now.y]+1)
{
dist[nx][ny]=dist[now.x][now.y]+1;

if(!vis[nx][ny])
{
vis[nx][ny]=1;
que.push(point(nx,ny));
}
}
}
}
}

int main()
{
scanf("%d%d",&M,&N);
int i,j;
char str[MAXN+10];
for(i=1;i<=M;++i)
{
scanf("%s",str+1);

for(j=1;j<=N;++j)
G[i][j]=(str[j]=='1');
}

Spfa();

for(i=1;i<=M;++i)
{
for(j=1;j<N;++j)
printf("%d ",dist[i][j]);
printf("%d\n",dist[i][N]);
}
}

08-17 364

01-25 929
03-09 7011
02-09 615
07-13 102
10-08 623
03-01 366
02-26 31
10-08 881
01-22 1万+
09-16 582