~~~~
題意: 給你一個R*C的圖,求其由圖中連通‘#“所組成的矩形的個數。
注意:If the ships
were placed correctly (i.e., there are only rectangles that do not touch each other even with a corner), print the sentence "There are S ships." where S is the number of ships. Otherwise,
print the sentence "Bad placement.".
所以若有一組連通的’#‘不能組成矩形,則輸出 Bad placement。
題目鏈接:http://poj.org/problem?id=1856
~~~~
思路:對每個’#‘進行DFS,求其’#‘的個數s(就是面積)。DFS同時,記錄y可以搜到的最左和最右位置,記錄x可以搜到的最上和最下位置。
則若 s==(r-l+1)*(u-d+1),則 tot++..
~~~~
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<string>
#include<queue>
#define N 1111
using namespace std;
int tot,n,m;
int s,l,r,u,d;
char g[N][N];
bool ok(int x,int y)
{
return (x>=0 && x<n && y>=0 && y<m && g[x][y]=='#');
}
void dfs(int x,int y)
{
s++;
l=min(y,l); u=min(u,x);
r=max(y,r); d=max(d,x);
g[x][y]='.';
for(int i=-1;i<=1;i++) //八個方向進行搜索。
for(int j=-1;j<=1;j++)
if(ok(x+i,y+j)) dfs(x+i,y+j);
return ;
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
if(n==0 && m==0)
break;
for(int i=0;i<n;i++)
scanf("%s",g[i]);
int tot=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(g[i][j]=='#')
{
s=0;
l=r=j;
u=d=i;
dfs(i,j);
if(s==(r-l+1)*(d-u+1))
tot++;
else i=n,j=m,tot=-1; //跳出循環。
}
}
}
if(tot<0) printf("Bad placement.\n");
else printf("There are %d ships.\n",tot);
}
return 0;
}