简体   繁体   中英

DFS for Graph, mark as visited

I'm implementing a DFS for a (linked list) Graph.

My graph structure example: http://i.imgur.com/Pm9jC.png

As you can see, there are many nodes named "a". They're the same in terms of vertex but they're actually different in terms of node. Implementing DFS involves marking "a" as visited at some point. This seems easy but I hope you can see my problem here. There are many "a" to mark as visited. I hope I'm doing something wrong here.

Problem: - First mark "a" as visited and push it onto stack s. this effectively mark node "a" in the 1st adjacency linked list as visited but all other nodes "a" in other adjacency linked lists are still marked as "not visited". - Then consider "b" as it is the first unvisited adjacent vertex to "a". mark it as visited and push it onto the stack s. - Now we're exploring "b". From the 2nd adjacency linked list, The adjacent vertex to "b" is "a" and this one is unvisited, so we push it onto the stack again. Wrong!

Of course, I can write a markVisit($vertex) method which mark all occurrences of "a" as visited at once, but I don't think I have the right approach in my implementation above. Thanks for your help.

markVisit($vertex) should be correct, you need to remember which vertexes you already visited. DFS concerns vertexes, not edges.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM