题目描述
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A11 to AHW represent the colors of the squares. Aij is # if the square at the i-th row from the top and the j-th column from the left is black, and Aij is . if that square is white.
We will repeatedly perform the following operation until all the squares are black:
Every white square that shares a side with a black square, becomes black.
Find the number of operations that will be performed. The initial grid has at least one black square.
Constraints
·1≤H,W≤1000
·Aij is # or …
·The given grid has at least one black square.
输入
Input is given from Standard Input in the following format:
H W
A11A12…A1W
:
AH1AH2…AHW
输出
Print the number of operations that will be performed.
样例输入
3 3
…
.#.
…
样例输出
2
提示
After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.
思路
多点找最短路
代码实现
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int N=1010;
const int mod=1000000007;
const double eps=1e-10;
int n,m,ans;
bool color[N][N];
int dis[N][N];
queue<P> qu;
int to[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void bfs()
{
while(qu.size())
{
P tmp=qu.front();
qu.pop();
for(int i=0;i<4;i++)
{
int ax=tmp.first+to[i][0],ay=tmp.second+to[i][1];
if(ax<=0 || ax>n || ay<=0 || ay>m || dis[ax][ay]<=dis[tmp.first][tmp.second]+1) continue;
dis[ax][ay]=dis[tmp.first][tmp.second]+1;
ans=max(ans,dis[ax][ay]);
qu.push(P(ax,ay));
}
}
}
int main()
{
//freopen("a.txt","r",stdin);
scanf("%d%d",&n,&m);
getchar();
for(int i=1;i<=n;i++)
{
char c;
for(int j=1;j<=m;j++)
{
c=getchar();
if(c=='#')
{
color[i][j]=true;
dis[i][j]=0;
qu.push(P(i,j));
}
else dis[i][j]=mod;
}
getchar();
}
bfs();
printf("%d\n",ans);
return 0;
}