It is also a typical problem to find the connected block with DFS, and the process of multi-dimensional array connecting block is also called "seed filling".
We add numbers to the connected blocks that are traversed each time, so that you can avoid a lattice access multiple times. The typical problem is the "eight-block problem". That is, any two squares are located adjacent to each other (up and down diagonally a total of eight positions), then in a connected block. Typical example: HDU 1241 oil deposits
Portal: http://acm.hdu.edu.cn/showproblem.php?pid=1241
Title Description: input m row n column character matrix, statistical character "@" to form the number of eight connected blocks.
Test Instructions Analysis: Read data, through a double loop traversal of the graph, encountered ' @ ' and has not been accessed->dfs its connected block and labeled--output
Code (for reference only):
#include <cstdio>#include<cstring>Const intMAXN = -+Ten;CharA[MAXN][MAXN];intN, M, IDX[MAXN][MAXN];voidDfsintRintCintID) { if(R <0|| R >= m | | C <0|| C >= N)return ; if(Idx[r][c] >0|| A[R][C]! ='@')return ; IDX[R][C]=ID; for(inti =-1; I <=1; i++) for(intj =-1; J <=1; J + +) if(I! =0|| J! =0) Dfs (R+i, c+j, id);}intMain () { while(~SCANF ("%d%d", &m, &N)) { if(n = =0&& m = =0) Break; for(inti =0; I < m; i++) scanf ("%s", A[i]); memset (IDX,0,sizeof(IDX)); intCNT =0; for(inti =0; I < m; i++) for(intj =0; J < N; J + +) if(Idx[i][j] = =0&& A[i][j] = ='@') Dfs (I, J, + +)CNT); printf ("%d\n", CNT); } return 0;}
View Code
DFS Getting started two---DFS seeking connectivity blocks