dfs:连通块
题目:有一个大小为N x M的园子,雨后积起了水。八连通的积水被认为是连接在一起的。清求出园子里总共有多少水洼?
(八连通指的是图中相对W的*部分),W表示积水,*表示没有积水
例如:
W........WW. .WWW.....WWW ....WW...WW. .........WW. .........W.. .W.......W.. .W.W.....WW. W.W.W.....W. .W.W......W. ..W.......W.
输出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(); return 0; }
#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) { return 0; }
#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) { return 0; }