Lake Counting
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 17917 Accepted: 9069
Description
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
Input
Line 1: Two space-separated integers: N and M
Lines 2..N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
Output
- Line 1: The number of ponds in Farmer John’s field.
Sample Input
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
Sample Output
3
这一题就是油田问题的翻版,题目大意就是说找出W组成的块(一个块是几个W连接在一起的,可能通过斜线也能连接。)有几个。
题目很简单,循环找到W然后将与其连接的置为‘.’。块数+1,就可以了。
下面是两种做法:
深搜:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "math.h"
using namespace std;
const int maxn = 1e2+5;
char map[maxn][maxn];
int n,m;
int changeX[8]={0,0,1,1,1,-1,-1,-1};
int changeY[8]={1,-1,1,-1,0,1,-1,0};
int check(int x,int y){
if(x<0||y<0||x>n||y>m||map[x][y]!='W') return 0;
return 1;
}
void dfs(int x,int y){
int i;
for(i=0 ; i<8 ; i++){
int nowX = x+changeX[i];
int nowY = y+changeY[i];
if(check(nowX,nowY)){
map[nowX][nowY]='.';
dfs(nowX,nowY);
}
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
int ans=0;
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
cin>>map[i][j];
}
}
for(int i=0 ;i<n ; i++){
for(int j=0 ;j<m ; j++){
if(map[i][j]=='W'){
dfs(i,j);
ans++;
}
}
}
printf("%d\n",ans);
}
return 0;
}
广搜:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "math.h"
#include "queue"
using namespace std;
const int maxn = 1e2+5;
char map[maxn][maxn];
int n,m;
int ans;
int changeX[8]={0,0,1,1,1,-1,-1,-1};
int changeY[8]={1,-1,1,-1,0,1,-1,0};
struct FYJ{
int x;
int y;
};
int check(int x,int y){
if(x<0||y<0||x>n||y>m||map[x][y]!='W')
return 0;
return 1;
}
void BFS(int x,int y){
queue<FYJ>q;
FYJ now,to;
now.x=x; now.y=y;
q.push(now);
while(!q.empty()){
now = q.front();
q.pop();
for(int i=0 ; i<8 ; i++){
to.x=now.x+changeX[i];
to.y=now.y+changeY[i];
if(check(to.x,to.y)){
q.push(to);
map[to.x][to.y]='.';
}
}
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
ans = 0;
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
cin>>map[i][j];
}
}
for(int i=0 ; i<n ; i++){
for(int j=0 ; j<m ; j++){
if(map[i][j]=='W'){
ans++;
BFS(i,j);
}
}
}
printf("%d\n",ans);
}
return 0;
}