作者: 一字马胡
转载标志 【2017-12-10】
更新日志
日期 | 更新内容 | 备注 |
---|---|---|
2017-12-10 | 学习dfs | 关于dfs的算法问题 |
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
Solve
只要能连接在一起的"w"都属于一个lake,那么现在的目标很明确了,需要将那些可以连接在一起的w都连接在一起,对于任意一个Element,要么是"w",要么是".",一个“w”可以连接和它相连的8个方向的w,所以对于每一个“w” Element,需要变量它的相连的8个方向,并且当方向某个方向上也是“w”的时候就需要合并,并且状态转移到这8个方向上,开始新一轮的合并工作,直到遇到边界,或者遇到“.” Element,那么就可以停止了,这里面的递归特性也是很明显的,解决本题的方法是一种称为dfs的搜索技术,从任意一个“w”开始,搜索其周围的8个方向。
所谓dfs(深度优先搜索),表示其从某个状态出发,不断的转移状态到可达的状态,一直到无法再转移状态,也就是再也没有可达的状态了,然后就进行回退操作,回到前一步的状态,继续转移到其他没有转移过的状态,这样不断的进行重复尝试,直到找到最终的解,下面是一个比较形象的状态转移图,其中的数字表示状态的转移步骤:
dsf下面展示了本题的一个解决方案,可以根据上面的图片进行理解dfs的搜索路径。
/*
@poj 2386
*/
#include<iostream>
using namespace std;
#define FOR(i,j,n,m) for(int i=0;i<n;i++) for(int j=0;j<m;j++)
int n, m;
char maze[101][101];
//(x,y)为当前的搜索位置
void dfs(int x, int y) {
//从(x,y)出发,将所有联通的点都遍历
maze[x][y] = '.';
int dx, dy;
//遍历8个方向
for (dx = -1; dx <= 1; dx++){
for (dy = -1; dy <=1 ; dy++){
int nx = x + dx;
int ny = y + dy;
if (nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] == 'W') {
dfs(nx, ny);
}
}
}
}
int main() {
int i, j;
cin >> n >> m;
FOR(i, j, n, m) cin >> maze[i][j];
int ans = 0;
FOR(i, j, n, m) {
if (maze[i][j] == 'W') {
dfs(i, j);
ans++;
}
}
cout << ans << endl;
return 0;
}
网友评论