The DFS implementation steps are as follows:
① Access vertex v and mark that V has accessed
② Find the first vertex W of V
③ If W exists, the execution continues; otherwise, the algorithm ends.
④ If W is not accessed, use DFS to recursively access W
⑤ Search for the next adjacent node of V, mark it as W, and go to step ③
For DFS, the access order is
A B D C E
The pseudocode is as follows:
Vector <int> G [maxn] int vis [maxn] void DFS (int u) {vis [u] = 1; // set it to int d = G [u]. size () // obtain all the adjacent nodes of vertex u. The number is d For (INT I = 0; I <D; I ++) {int v = G [u] [I]; // scan all adjacent vertices. If no, DFS accesses this vertex if (! Vis [v]) DFS (v );}}
Complete the Code:
# Include <iostream> using namespace STD; # define vertexsize 10int visit [vertexsize]; typedef struct {int weight [vertexsize] [vertexsize];} graph; void initiate_graph (graph * G, int N) {int I, j; for (I = 0; I <n; I ++) visit [I] = 0; For (j = 0; j <N; j ++) {if (I = J) g-> weight [I] [J] = 0; else G-> weight [I] [J] = 0x7fff;} void insertedge (graph * g, int V, int W, int weight, int N) {If (v <0 | V> = n | W <0 | W> = N) {cout <"overflow! "<Endl;} G-> weight [v] [W] = weight;} void DFS (graph * g, int U, int N) {cout <u <"; visit [u] = 1; int I; for (I = 0; I <n; I ++) {If (G-> weight [u] [I]> 0 & G-> weight [u] [I] <0x7fff &&! Visit [I]) {visit [I] = 1; DFS (G, I, n) ;}} void main () {graph G; int N, edge; cout <"Enter the number of vertices in the graph:" <Endl; CIN> N; cout <"Enter the number of edges in the graph" <Endl; cin> edge; initiate_graph (& G, n); int I, P1, P2, weight; cout <"Enter vertex-weight:" <Endl; for (I = 0; I <edge; I ++) {CIN> P1> P2> weight; insertedge (& G, P1, P2, weight, n);} DFS (& G, 0, n); System ("pause ");}
How to implement deep priority traversal (DFS)