The implementation of depth-first search is simple, and two factors need to be controlled:
1. Elements that have already been accessed are no longer accessible, and the elements that are inaccessible are added to the actual topic (barriers)
2. Cross-border This situation is not allowed
Take the 1312 Red and Black as an example, this is a typical DFS topic
Portal: http://acm.hdu.edu.cn/showproblem.php?pid=1312
The main idea: ' @ ' stands for the starting position, '. ' Represents the black point (which can be traversed), ' # ' represents the red dot (barrier) requires statistics to cover up to how many black dots
Topic Analysis: Determine starting position, start DFS, if not illegal location, count once, recursive search four directions (up, down, left, right)-end
Attach My code (for reference only):
#include <cstdio>#include<cstring>Const intMAXN = -+Ten;CharA[MAXN][MAXN];intW, H, IDX[MAXN][MAXN], CNT;intDfsintRintCintID) { if(R <0|| R >= H | | C <0|| C >= W)return 0; if(Idx[r][c] >0|| A[R][C] = ='#')return 0; IDX[R][C]=ID; CNT++; for(inti =-1; I <=1; i++) for(intj =-1; J <=1; J + +) if((i = =0&& J! =0)|| (I! =0&& J = =0)) Dfs (R+i, c+j, id);}intMain () {intR, C; while(~SCANF ("%d%d", &w, &h)) {CNT=0; if(W = =0&& h = =0) Break; for(inti =0; I < H; i++) scanf ("%s", A[i]); memset (IDX,0,sizeof(IDX)); for(inti =0; I < H; i++) for(intj =0; J < W; J + +) if(A[i][j] = ='@') {R=i; C=J; } DFS (R, C,1); printf ("%d\n", CNT); } return 0;}please refer to it.
One of the Dfs getting Started