* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
6.5 KiB
Graph traversal
A tree represents one-to-many relationships, whereas a graph allows more freedom and can represent arbitrary many-to-many relationships. We can therefore view a tree as a special case of a graph. Accordingly, tree traversal is also a special case of graph traversal.
Both graphs and trees use search algorithms for traversal. Graph traversal can likewise be divided into two types: breadth-first traversal and depth-first traversal.
Breadth-first traversal
Breadth-first traversal visits vertices from near to far. Starting from a vertex, it always visits the nearest vertices first and expands outward layer by layer. In the figure below, we start at the top-left vertex and visit all its adjacent vertices, then visit all the adjacent vertices of the next vertex, and so on until every vertex has been visited.
Algorithm implementation
BFS is usually implemented with a queue, as shown in the code below. A queue's first-in, first-out behavior fits the near-to-far order of BFS.
- Enqueue the starting vertex
startVetand begin the loop. - In each iteration, dequeue the vertex at the front and record the visit, then enqueue all its adjacent vertices at the rear.
- Repeat step
2.until every vertex has been visited.
To avoid visiting a vertex more than once, we use a hash set visited to track which vertices have already been visited.
!!! tip
A hash set can be viewed as a hash table that stores only `key` entries, with no `value` entries. Adding, removing, looking up, and modifying a `key` take $O(1)$ time. Because every `key` is unique, hash sets are commonly used to remove duplicate data.
[file]{graph_bfs}-[class]{}-[func]{graph_bfs}
The code is fairly abstract; compare it with the figure below to build your understanding.
!!! question "Is the breadth-first traversal order unique?"
No. Breadth-first traversal only requires vertices to be visited from near to far; **vertices at the same distance may be visited in any order**. In the figure above, vertices $1$ and $3$ can be visited in either order, and vertices $2$, $4$, and $6$ can also be visited in any order.
Complexity analysis
Time complexity: Every vertex is enqueued and dequeued once, taking O(|V|) time. While traversing adjacent vertices, every edge is visited 2 times because the graph is undirected, taking O(2|E|) time. The total time is O(|V| + |E|).
Space complexity: The list res, hash set visited, and queue que each contain at most |V| vertices, requiring O(|V|) space.
Depth-first traversal
Depth-first traversal follows a path as far as possible and returns when it can go no farther. In the figure below, we start at the top-left vertex and move to an adjacent vertex of the current vertex, continuing until we reach a dead end. We then return and explore another path as far as possible, repeating this process until every vertex has been visited.
Algorithm implementation
This pattern of going as far as possible and then returning is usually implemented with recursion. As with breadth-first traversal, we use a hash set visited to track visited vertices and avoid visiting them again.
[file]{graph_dfs}-[class]{}-[func]{graph_dfs}
The figure below shows the steps of depth-first traversal.
- Straight dashed lines show recursive descent, where a new recursive call begins to visit another vertex.
- Curved dashed lines show backtracking, where a recursive call has returned to the point from which it was made.
To deepen your understanding, follow the figure below alongside the code and mentally simulate (or draw on paper) the entire DFS process, including when each recursive call begins and returns.
!!! question "Is the depth-first traversal order unique?"
Like breadth-first traversal, depth-first traversal does not have a unique order. From any vertex, we can explore in any direction first: rearranging the order of adjacent vertices still produces a depth-first traversal.
For example, in tree traversal, "root $\rightarrow$ left $\rightarrow$ right", "left $\rightarrow$ root $\rightarrow$ right", and "left $\rightarrow$ right $\rightarrow$ root" correspond to preorder, inorder, and postorder traversal. They use three different visiting priorities, yet all are depth-first traversals.
Complexity analysis
Time complexity: Every vertex is visited 1 time, taking O(|V|) time, and every edge is visited 2 times, taking O(2|E|) time. The total time is O(|V| + |E|).
Space complexity: The list res and hash set visited each contain at most |V| vertices, and the maximum recursion depth is |V|, so the space complexity is O(|V|).























