bfs and dfs Template

Bfs In general, the search for the shortest path is the same, and the path of each step is the same. The search efficiency of bfs will be higher. It is not like dfs to pass a parameter and it is done. Generally, the structure is used to store the information of this state.
Bfs needs to use the queue to achieve:
1. Initially put the starting point in the queue, and mark the starting point for access.
2. If the queue is not empty, remove an element x from the queue, otherwise the algorithm ends.
3. Visit all points v connected to x. If v is not visited, put V into the queue and mark it as visited
. 4. Repeat step 2.

void bfs(起始点){
	将启示点放入队列中;
	标记起点访问; 
	while(如果队列不为空){
		访问队列中队首元素;
		删除队首元素;
		for(x 所有相邻点){
			if(该点未被访问过且合法){
				将该点加入队列末尾; 
			} 
		} 
	}
	队列为空,广搜结束; 
} 

dfs
dfs is suitable for those seeking the number of feasible paths, while bfs is suitable for finding the shortest path and the like (because once found, it is the shortest).

在这里插入代码片

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325679677&siteId=291194637