1. Application of BFS
Figure BFSAlgorithmIt can be used to find the shortest path from a vertex to other vertices. If BSF is used for each vertex in the graph once, you can find the shortest path from each vertex to other vertices.
2. DFS applications
2.1 topological sorting
The DFS algorithm can be used to find a directed acyclic graph topological sorting.CodeAs follows:
From the pseudo code, we can see that each node in the figure is sorted by the completion time in descending order. Then output the sorted results in sequence to obtain a topological sorting.
2.2 find all strong Unicom branches in the figure
The DFS algorithm can also find all strongly connected branches of a directed graph. The pseudocode is as follows:
The algorithm first calls DFS (g) to construct a depth-first search forest, and fl the completion time of each node f [u]. Calculate the transpose matrix GT represented by the matrix in Figure G, and then call DFS () again on the GT, but this time, instead of randomly accessing the node, it is based on the first DFS () f [u] of each node in descending order. This time, a deep-Priority Search forest is constructed. Each deep-Priority Search Tree is a strongly connected branch of the source image.
You may wonder why this algorithm is a little weird? Why can't I fix a DFS? Why do we need to calculate the G transpose matrix? Why is the second DFS sorted in descending order of F [u?
For the reason, please refer to the 339th page of the Chinese version of Introduction to algorithms, which is complicated and cannot be understood in one or two sentences.
The implementation of the strongly_connected component algorithm is not complete. To be continued ......