How to realize the DFS and BFS of C++
This article mainly explains "how to realize the DFS and BFS of C++". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to achieve the DFS and BFS of C++".
DFS and BFS
For nonlinear structures, traversal will be a problem in the first place. Like the traversal of a binary tree, there are depth-first search (DFS) and breadth-first search (BFS). The difference is that each vertex in the graph has no relationship between ancestors and descendants, so the pre-order, middle order and post-order are no longer meaningful. Following the traversal of a binary tree, you can easily complete DFS and BFS, but note that there may be loops in the diagram, so you must mark the visited vertices.
The most basic directed weighted network
# ifndef Graph_H # define Graph_H # include # include using namespace std; # include "Graphmem.h" template class Network {public: Network () {} Network (dist maxdist) {data.NoEdge = maxdist;} ~ Network () {} bool insertV (name v) {return data.insertV (v);} bool insertE (name v1, name v2, dist cost) {return data.insertE (v1, v2, cost) } name& getV (int n) {return data.getV (n);} int nextV (int m, int n =-1) {return data.nextV (m, n);} int vNum () {return data.vNum;} int eNum () {return data.eNum;} protected: bool* visited; static void print (name v) {cout