Common version: Unified version will have multi-copy vertex in the
queue. We can improve it as below: 1) when you add it to queue, visit
it. In this way, avoid add multi-copy vertex in queue 2) Because All the
vertex in queue is visited, when you pop it, you don’t need to judge if
it’s visisted.
Conclusion, just remember unified version. 1) popcurrent, push neighbor, 2) check two unvisited
unified version will push two nodes into stack or queue, so for
BFS, you can visit and push at the same time, in this way,
you don’t need to check current if it is unvisited.
For DFS, you can’t use this way, because you can only visit
only one neighbor, or it will become BFS. so each time, you
just push one node into stack. It leads to two other versions.
recursive version, and loop version.
Path is saved in the stack. when you quit while loop. just pop up each
position from stack, then you get a path. But for BFS, you need extra
information to save parent information.