These traversal algorithms are conceptually the same as the ones introduced in the tree section.
In a depth first search, we start with an arbitrary node as a root and explore each neighbor fully before exploring the next one.
Implementation:
Runtime: O(V + E)
Example interview question using DFS:
In breadth first search, we pick an arbitrary node as the root and explore each of its neighbors before visiting their children. Breadth first search is the better suited at finding the shortest path between two nodes.
Implementation:
Example interview question using BFS:
Runtime: O(V + E)