Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 44936 | Accepted: 22205 |
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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
本题大意:给你一个N*M的矩阵由 ' W ' , ' . '构成,求由' W '组成的连通区域有几个
思路:DFS深度搜索
AC代码:
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#define MAXN 110
using namespace std;
typedef long long ll;
int m, n;
char str[MAXN][MAXN];
int vis[MAXN][MAXN];
//定义一个八个方向的方向数组,表示下次可以移动的位置
int dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
void DFS(int x, int y)
{
str[x][y] = '.';//将W换成' . ' ,下次遇到时不会重复检索,也可以定义一个数组来做
for(int i = 0; i < 8; i++)
{
int dx = x + dir[i][0];
int dy = y + dir[i][1];
//可以通过剪枝来做,亦可以跟我一样直接写出满足的条件进入递归
// if(dx < 0 || dy < 0 || dx >= n || dy >= m) continue;
// if(str[dx][dy] == '.') continue;
if(str[dx][dy] == 'W' && dx >= 0 && dy >= 0 && dx < n && dy < m)
{
DFS(dx, dy);
}
}
}
int main()
{
int stax, stay, num = 0;
scanf("%d %d", &n, &m);
for(int i = 0; i < n; i++) scanf("%s", str[i]);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(str[i][j] == 'W')
{
stax = i, stay = j;
num ++;//每一次找到一个W就可以加一
DFS(stax, stay);
}
}
}
printf("%d\n", num);
return 0;
}