首页 > 代码库 > UVa572 Oil Deposits (DFS求连通块)

UVa572 Oil Deposits (DFS求连通块)

链接:http://acm.hust.edu.cn/vjudge/problem/19435
分析:DFS求图的连通块。每次从图中找出一个未访问过的‘@’开始递归遍历它周围的‘@’格子,将访问到的‘@’标上id存在idx数组中,dfs的次数就是连通块的个数。
DFS遍历用递归实现,BFS用队列实现。
DFS和BFS实现种子填充:https://zh.wikipedia.org/wiki/Flood_fill

 1 #include <cstdio> 2 #include <cstring> 3  4 const int maxn = 100 + 5; 5  6 int m, n, idx[maxn][maxn]; 7 char pic[maxn][maxn]; 8  9 void dfs(int r, int c, int id) {10     if (r < 0 || r >= m || c < 0 || c >= n) return;11     if (idx[r][c] || pic[r][c] != @) return;12     idx[r][c] = id;13     for (int dr = -1; dr <= 1; dr++)14         for (int dc = -1; dc <= 1; dc++)15              if (dr != 0 || dc != 0) dfs(r + dr, c + dc, id);16 }17 18 int main() {19     while (scanf("%d%d", &m, &n) == 2 && m && n) {20         for (int i = 0; i < m; i++) scanf("%s", pic[i]);21         memset(idx, 0, sizeof(idx));22         int cnt = 0;23         for (int i = 0; i < m; i++)24             for (int j = 0; j < n; j++)25                 if (idx[i][j] == 0 && pic[i][j] == @) dfs(i, j, ++cnt);26         printf("%d\n", cnt);27     }28     return 0;29 }

 

UVa572 Oil Deposits (DFS求连通块)