所谓灌水法?其实就是一个bfs了。
注意此题要求判断是否合法,只需要记录经过的点数,判断它是否是矩形的面积即可。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
using namespace std;
bool vis[1005][1005];
int n,m,map[1005][1005],flag=0,cnt=0;
int dx[]={0,0,1,0,-1},dy[]={0,1,0,-1,0};
struct code
{
int x,y;
};
queue <code> q;
char s[1005];
bool judge(int x,int y)
{
if ((x>=1) && (x<=n) && (y>=1) && (y<=m) && (map[x][y]==1) && (vis[x][y]==false))
return true;
return false;
}
void bfs(int bx,int by)
{
int cc=1,maxx=bx,maxy=by;
while (!q.empty())
q.pop();
code begin;
begin.x=bx;begin.y=by;
q.push(begin);
vis[bx][by]=true;
while (!q.empty())
{
code head=q.front();
q.pop();
for (int i=1;i<=4;i++)
{
if (judge(head.x+dx[i],head.y+dy[i])==true)
{
cc++;
maxx=max(maxx,head.x+dx[i]);
maxy=max(maxy,head.y+dy[i]);
code now;
now.x=head.x+dx[i];now.y=head.y+dy[i];
vis[now.x][now.y]=true;
q.push(now);
}
}
}
if ((maxx-bx+1)*(maxy-by+1)!=cc) flag=1;
}
int main()
{
memset(vis,false,sizeof(vis));
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
{
scanf("%s",s);
for (int j=0;j<m;j++)
{
if (s[j]==‘.‘) map[i][j+1]=0;
else map[i][j+1]=1;
}
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if ((vis[i][j]==false) && (map[i][j]==1))
{
cnt++;
bfs(i,j);
if (flag==1)
{
printf("Bad placement.\n");
return 0;
}
}
printf("There are %d ships.\n",cnt);
return 0;
}