# Algorithm question-image depth first Traversal

Source: Internet
Author: User

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}

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.