<title>DFS: Connected blocks</title> DFS: Connected blocks
Title: There is a garden of size n x m, which accumulates water after rain. Eight connected water is considered to be connected together. How many puddles are there in total in the garden?
(eight-connected refers to the figure of the relative W of the * section), w means water, * indicates no water
For example:
W........ Ww.. WWW.....WWW....WW...WW..........WW..........W...W.......W...W.W.....WW.W.W.W.....W..W.W......W...W.......W.
Output 3
#include <stdio.h>int N;int M;Char arr[102] [102];void DFS(int x,int y) {if(X < 0 | | Y < 0 | | x >= N | | y >= M | | arr[x][y] = ='. ') {return; } Arr[x][y] ='. '; for(int I=-1; I <= 1; i++) { for(int J=-1; J <= 1; J + +) {int NX= x + i;int NY= y + j; DFS (NX, NY); } }}void Solve(void) {int ans= 0; for(int I= 0; i < N; i++) { for(int J= 0; J < M; J + +) {if(Arr[i][j]! ='. ') {DFS (i, j); ans++; }}} printf ("%d\n", ans);}int Main(void) {printf ("Input the N and m\n"); scanf"%d%d", &n, &m); for(int I= 0; i < N; i++) {scanf ('%s ', Arr[i]); } solve ();return0;}
#include <cstdio>Const int MAXN= 105;int N;int m;Char g[MAXN] [MAXN];void DFS(int x,int y) {G[x][y] ='. '; for(int DX=-1; DX <= 1; dx++) { for(int Dy=-1; DY <= 1; dy++) {int NX= x + dx;int NY= y + dy;if(0 <= NX && NX < n && 0 <= ny && NY < m && G[nx][ny] = =' W ') {DFS (NX, NY); } } }}void Solve() {int Res= 0; for(int I= 0; I < n; i++) { for(int J= 0; J < M; J + +) {if(G[i][j] = =' W ') {DFS (i, j); res++; }}} printf ("%d\n", res);}int Main(void) {return0;}
#include <cstdio>Const int MAXN= 105;BOOL v[MAXN] [MAXN];int g[MAXN] [MAXN];int N;int m;void DFS(int x,int y) {V[x][y] = 1; for(int I=-1; I <= 1; i++) { for(int J=-1; J <= 1; J + +) {int NX= x + i;int NY= y + j;if(V[nx][ny] = = 0 && 0 <= NX && NX < n && 0 <= ny && NY <= M && g[nx][ny ] ==' W ') {DFS (NX, NY); } } }}void Solve() {int Res= 0; for(int I= 0; I < n; i++) { for(int J= 0; J < M; J + +) {Dfs (i, j); res++; }} printf ("%d\n", res);}int Main(void) {return0;}
DFS: Connected blocks