题意
在一片空地上,出现了若干水洼,对于一个有水的格子,他的八连通格子(上下左右左上左下右上右下)都可以看成和他连通形成一个大水洼。现在给你空地上水的配布,你要数出有多少个水洼。
思路
典型的“水洼问题”,利用DFS解决连通性问题是十分方便的。本题只要能够正确实现DFS就可以通过了,实现DFS的要点主要是正确地使用标记和正确的递归写法。对于DFS的实作原理不太理解的话请先思考树的先序遍历,可以参考我写的这篇文章。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
#include <iostream> #include <algorithm> #include <queue> #include <vector> #include <cstdlib> #include <cstdio> #include <string> #include <cstring> #include <ctime> #include <iomanip> #include <cmath> #include <set> #include <stack> #include <cmath> #include <map> using namespace std; int N,M; int dir[8][2] = {{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}}; char grid[102][102]; bool isValid(int y,int x){ if (y < 1 || y > N) { return false; } if (x < 1 || x > M) { return false; } return grid[y][x] == 'W'; } int vis[102][102]; bool dfs(int cury,int curx,int id){ if (!vis[cury][curx] && isValid(cury, curx)) { vis[cury][curx] = id; }else{ return false; } for (int i = 0; i < 8; i++) { int newy = cury + dir[i][0]; int newx = curx + dir[i][1]; if (isValid(newy, newx) && !vis[newy][newx]) { dfs(newy, newx, id); } } return true; } int main(){ while (scanf(" %d %d",&N,&M) != EOF) { for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf(" %c",&grid[i][j]); } } memset(vis, 0, sizeof(vis)); int res = 1; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (dfs(i, j, res)) { res++; } } } cout << --res << endl; } return 0; } |