代码:
#include <bits/stdc++.h> using namespace std; const int maxn = 105; int n, k, m; int a[maxn][maxn]; int vis[maxn][maxn]; // 记录是否已被计算过 int num = 0; int dx[5] = {-1, 0, 0, 1}; // 下,右,左,上 int dy[5] = {0, 1, -1, 0}; void dfs(int x, int y) // 已经选到了i,j { vis[x][y] = 1; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (a[nx][ny] == 0 || vis[nx][ny] == 1) continue; dfs(nx, ny); } } int main() { cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { char u; cin >> u; a[i][j] = u - '0'; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++)//每个位置都要dfs { if (a[i][j] != 0 && vis[i][j] == 0) { dfs(i, j); num++; } } } cout << num; }