For the principle and method, see depth-first traversal of the image.
C code in the textbook,Recursion:
1 // textbook method, adjacent Table 2 bool visited [Max]; 3 void visitfunc (int v); 4 5 void dfstraverse (graph G) 6 {7 for (V = 0; v <G. vexnum; ++ v) // The initial access ID is false 8 visited [v] = false; 9 for (V = 0; v <G. vexnum; ++ v) // search for 10 if (! Visited [v]) 11 DFS (G, V); 12} 13 14 void DFS (graph G, int v) 15 {16 visited [v] = true; 17 visitfunc (V); 18 for (W = firstadjvex (G, V); W = nextadjvex (G, V, W) // traverse the adjacent Table 19 if (! Visited [w]) 20 DFS (G, W); 21}
IterationVersion:
1 // use the stack to maintain the order, iterate 2 void dfstraverse (graphnode * g) 3 {4 unordered_map <graphnode *, bool> visited; 5 stack <graphnode *> unvisited; 6 unvisited. push (g); // The first node into the stack 7 while (! Unvisited. Empty () 8 {9 cur = unvisited. Top (); 10 unvisited. Pop (); 11 12 for (W = G. Neighbor; W! = NULL; W = W-> next) // traverse the adjacent Table 13 if (visited. find (W-> node) = visited. end () 14 {15 unvisited. push (W-> node); 16 visited [w-> node] = true; 17} 18 19 visitfunc (cur); 20} 21}