Depth First Search (DFS) C++

Depth First Search (DFS)

Depth-first search is one of the means of search. It starts from a certain state, and continues to transfer the state until it cannot be transferred, then returns to the state of the previous step, continues to transfer to other states, and repeats this way until the final solution is found.

Insert picture description here
The depth-first search (implicit) uses the stack for calculation. The stack supports push and pop operations, and data elements are last in, first out.

Example: Lake Counting (POJ No.2386)

Title description

There is a garden of size N * M, and water has accumulated after the rain. Eight connected standing water is considered to be connected together. Ask how many puddles are there in the garden? (Eight connectivity refers to the * part relative to W in the figure below)

***
*W*
***

Restrictions:
N,M <= 100

Sample input

N=10, M=12 The
garden is as shown below ('W' means stagnant water,'.' means no stagnant water)

W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.

Sample output

3

Topic analysis

From arbitrary Wstart, keep ‘.’replacing the adjacent part with . After one DFS, Wall W connected to the initial one are replaced ‘.’, so until there is no more W in the figure, the total number of DFS is the answer. The 8 directions correspond to a total of 8 state transitions. Each grid is called at most once as a parameter of DFS, so the complexity is O( 8×N×M) = O(N×M)

Code

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAX_N = 10001;
int N,M; 
char field[MAX_N][MAX_N+1];	//园子 

//现在位置( x, y ) 
void dfs(int x, int y){
    
    
	//将现在所在位置替换为 . 
	field[x][y] = '.';
	
	//循环遍历移动的8个方向 
	for(int dx = -1; dx<=1; dx++){
    
    
		for(int dy = -1; dy<=1; dy++){
    
    
			// 向x方向移动dx,向y方向移动dy,移动的结果为(nx, ny) 
			int nx = x + dx, ny = y + dy;
			// 判断(nx, ny)是不是在园子内,以及是否有积水 
			if(0<=nx && nx < N && 0<=ny && ny < M && field[nx][ny] =='W')
				dfs(nx,ny);
		}
	} 
	return ;
} 


int main(){
    
    
	cin >> N >> M;
	int res = 0;
	
	for(int i=0; i<N; i++){
    
    
		for(int j=0; j<M; j++)
			cin >> field[i][j];
	} 
	
	for(int i=0; i<N; i++){
    
    
		for(int j=0; j<M; j++)
			if(field[i][j] == 'W'){
    
    
				//从有W的地方开始dfs 
				dfs(i,j);
				res++; 
			}
	} 
	
	cout << res << endl;
	return 0;
} 

Guess you like

Origin blog.csdn.net/qq_44524918/article/details/109018058