Given a graph, we can use the O(V+E) DFS (Depth-First Search) or BFS (Breadth-First Search) algorithm to traverse the graph and explore the features/properties of the graph. Each algorithm has its own characteristics, features, and side-effects that we will explore in this visualization.
This visualization is rich with a lot of DFS and BFS variants (all run in O(V+E)) such as:
Remarks: By default, we show e-Lecture Mode for first time (or non logged-in) visitor.
Please login if you are a repeated visitor or register for an (optional) free account first.
当所选的图遍历算法运行时,将在次处显示动画。
Pro-tip: Since you are not logged-in, you may be a first time visitor who are not aware of the following keyboard shortcuts to navigate this e-Lecture mode: [PageDown] to advance to the next slide, [PageUp] to go back to the previous slide, [Esc] to toggle between this e-Lecture mode and exploration mode.
对于指定一个输入图,有两种不同的方法:
Another pro-tip: We designed this visualization and this e-Lecture mode to look good on 1366x768 resolution or larger (typical modern laptop resolution in 2017). We recommend using Google Chrome to access VisuAlgo. Go to full screen mode (F11) to enjoy this setup. However, you can use zoom-in (Ctrl +) or zoom-out (Ctrl -) to calibrate this.
If you arrive at this e-Lecture without having first explore/master the concept of Binary Heap and especially Binary Search Tree, we suggest that you explore them first, as traversing a (Binary) Tree structure is much simpler than traversing a general graph.
Quiz: Mini pre-requisite check. What are the Pre-/In-/Post-order traversal of the binary tree shown (root = vertex 0), left and right child are as drawn?
In = 4, 2, 3, 0, 1e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
In general graph, we do not have the notion of root vertex. Instead, we need to pick one distinguished vertex to be the starting point of the traversal, i.e. the source vertex s.
We also have 0, 1, ..., k neighbors of a vertex instead of just ≤ 2.
We may (or actually very likely) have cycle(s) in our general graph instead of acyclic tree,
be it the trivial one like u → v → u or the non-trivial one like a → b → c → a.
But fret not, graph traversal is an easy problem with two classic algorithms: DFS and BFS.
The closest analogy of the behavior of DFS is to imagine a maze with only one entrance and one exit. You are at the entrance and want to explore the maze to reach the exit. Obviously you cannot split yourself into more than one.
Ask these reflective questions before continuing: What will you do if there are branching options in front of you? How to avoid going in cycle? How to mark your own path? Hint: You need a chalk, stones (or any other marker) and a (long) string.
如果DFS在顶点 u 并且它有 X 个邻居,它会选择第一个邻居 V1 (通常是序号最小的那个顶点), 使用递归访问所有 V1可以到达的顶点, 最终返回顶点 u. DFS 接下来对其他的邻居做同样的事指导探索完成最后一个邻居 VX 和它所能触及到的顶点.
等下看了DFS的动画 这个冗长的解释会变得清晰起来。如果一个图是圈,之前的“尝试所有”的方法可能让DFS陷入循环。所以DFS的基本形式用一个大小为 V 个顶点的数组 status[u] 来确定两种情况 分别为 u 已经被访问过了 或者没有被访问过。只有当 u 还没有被访问过的时候 DFS才可以访问顶点 u.
当DFS没有路可走的时候它会跳出当前的递归 回去 到之前的顶点 (p[u], 看下一页).
DFS 用另一个大小为 V 个顶点数组 p[u] 来记住在DFS遍历路径上每一个顶点 u 的 parent/predecessor/previous(父/祖先/前)
最开始的顶点的祖先也就是 p[s] 被设定为-1也就是说它没有祖先 (因为最低的顶点是顶点0).
从一个源顶点 s 到一个可以到达的顶点 u 所生成的路径反过来 就是 DFS 生成树. 我们给这些 树路径 上 红色.
现在,忽略显示的伪代码中额外的 status[u] = explored 以及可视化中的 蓝色 和 灰色 边的存在 (将很快会解释)。
不用多说,让我们在这个 e-Lecture 的默认示例图上执行 (CP3 Figure 4.1)。DFS 的时间复杂度是 O(V+E) ,因为:
DFS 的he O(V+E) 时间复杂度只有当我们可以在 O(k) 时间内访问一个顶点的所有 k 个邻点时才可以实现。
Quiz: Which underlying graph data structure support that operation?
e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
BFS 与之前讨论过的非常相似,但有一些差异。
BFS 从源点 s 开始,但它在更深入之前使用 queue 尽最宽可能地将访问序列排序。
BFS 还是用大小为 V 节点的布尔数组来区分两种不同的状态:已访问节点和未访问节点(我们不会像使用 DFS 那样使用 BFS 来检测反向边)。
在此可视化中,我们还展示从未加权图中的相同源点 s 开始,此图的 BFS 生成树等于其 SSSP spanning tree.Without further ado, let's execute .
on the default example graph for this e-Lecture (CP3 Figure 4.3).Notice the Breadth-first exploration due to the usage of FIFO data structure: Queue?
BFS的时间复杂度是 O(V+E),因为:
对于DFS来说 O(V+E) 只有在用 邻接表 图数据结构 — 和DFS分析相同
到现在为止,我们可以用 DFS/BFS 去解决一些遍历图的问题变种:
多数的数据结构和算法课程只传授这些 DFS/BFS 的基本应用,尽管它们可以做更多...
We can actually augment the basic DFS further to give more insights about the underlying graph.
In this visualization, we use blue color to highlight back edge(s) of the DFS spanning tree. The presence of at least one back edge shows that the traversed graph (component) is cyclic while its absence shows that at least the component connected to the source vertex of the traversed graph is acyclic.
Back edge can be detected by modifying array status[u] to record three different states:
If DFS is now at vertex x and explore edge x → y and encounter status[y] = explored, we can declare x → y is a back edge (a cycle is found as we were previously at vertex y (hence status[y] = explored), go deep to neighbor of y and so on, but we are now at vertex x that is reachable from y but vertex x leads back to vertex y).
The edges in the graph that are not tree edge(s) nor back edge(s) are colored grey. They are called forward or cross edge(s) and currently have limited use (not elaborated).
Now try normal black circle, explored/blue circle, visited/orange circle) and back edge. Edge 2 → 1 will be discovered as a back edge as it is part of cycle 1 → 3 → 2 → 1 (similarly with Edge 6 → 4 as part of cycle 4 → 5 → 7 → 6 → 4).
on the example graph above with this new understanding, especially about the 3 possible status of a vertex (unvisited/我们可以使用以下简单的递归函数来打印出存储在数组 p 中的路径。可能的后续讨论:您能以迭代的形式写出来吗?(容易解决的)
method backtrack(u)
if (u == -1) stop
backtrack(p[u]);
output vertex u
要打印图中从源点到目标顶点 t 的路径,可以调用 O(V+E) DFS(s) (或 BFS(s)) ,然后调用 O(V) 去返回 (t)。示例: s = 0 和 t = 4,您可以调用
然后回溯 (4)。如果您被要求测试图中的节点 s 和一个(不同的)节点 t 是否可达,即直接连接(通过一条边)或间接连接(通过简单的非环路径),则可以调用 O(V+E) DFS(s) (或 BFS(s)) 并检查是否 status[t] = visited。
例子 1: s = 0 和 t = 4, 运行
并注意 status[4] = visited. 例子 2: s = 0 和 t = 7, 运行 并注意 status[7] = unvisited.我们可以通过简单地调用 O(V+E) DFS(s) (或 BFS(s)) 来枚举从无向图中的节点 s 可到达的所有节点(如上图的示例图所示),并枚举所有 status[v] = visited 的节点 v。
示例: s = 0,运行 并注意 status[{0,1,2,3,4}] = visited,因此它们都是从节点 0 可到达的节点,即它们形成一个连通分量(CC)。我们可以用如下的伪代码来计数连接部分(CCs)的数量:
CC = 0
for all u in V, set status[u] = unvisited
for all u in V
if (status[u] == unvisited)
CC++ // 我们可以用CC计数器的数量来标记CC
DFS(u) // 或者 BFS(u), 来标记它的成员为已访问
output CC // 上面的示例图的答案是3
// CC 0 = {0,1,2,3,4}, CC 1 = {5}, CC 2 = {6,7,8}
如果你想要给每一个CC你自己的标记 你可以修改一点 DFS(u)/BFS(u) 的代码
Quiz: What is the time complexity of Counting the Number of CCs algorithm?
e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
还有另一个可以被视为”简单“的 DFS(以及 BFS)应用:执行有向五环图(DAG)的拓扑排序 — 参见上面的示例。
我们可以使用 O(V+E) DFS 或 BFS 来执行有向无环图(DAG)的拓扑排序。
As of now, you have seen DFS/BFS and what it can solve (with just minor tweaks). There are a few more advanced applications that require more tweaks and we will let advanced students to explore them on their own:
Advertisement: The details are written in Competitive Programming book.
We can use the O(V+E) DFS or BFS (they work similarly) to check if a given graph is a Bipartite Graph by giving alternating color (orange versus blue in this visualization) between neighboring vertices and report 'non bipartite' if we ends up assigning same color to two adjacent vertices or 'bipartite' if it is possible to do such '2-coloring' process. Try or on the example Bipartite Graph.
Bipartite Graphs have useful applications in (Bipartite) Graph Matching problem.
Note that Bipartite Graphs are usually only defined for undirected graphs so this visualization will convert directed input graphs into its undirected version automatically before continuing. This action is irreversible and you may have to redraw the directed input graph again for other purposes.
We can modify (but unfortunately, not trivially) the O(V+E) DFS algorithm into an algorithm to find Cut Vertices & Bridges of an Undirected Graph.
A Cut Vertex, or an Articulation Point, is a vertex of an undirected graph which removal disconnects the graph. Similarly, a bridge is an edge of an undirected graph which removal disconnects the graph.
Note that this algorithm for finding Cut Vertices & Bridges only works for undirected graphs so this visualization will convert directed input graphs into its undirected version automatically before continuing. This action is irreversible and you may have to redraw the directed input graph again for other purposes. You can try to
on the example graph above.We can modify (but unfortunately, not trivially) the O(V+E) DFS algorithm into an algorithm to find Strongly Connected Components (SCCs) of a Directed Graph G.
An SCC of a directed graph G a is defined as a subgraph S of G such that for any two vertices u and v in S, vertex u can reach vertex v directly or via a path, and vertex v can also reach vertex u back directly or via a path.
There are two known algorithms for finding SCCs of a Directed Graph: Kosaraju's and Tarjan's. Both of them are available in this visualization. Try
and/or on the example directed graph above.We also have the 2-SAT Checker algorithm. Given a 2-Satisfiability (2-SAT) instance in the form of conjuction of clauses: (clause1) ^ (clause2) ^ ... ^ (clausen) and each clause is in form of disjunction of up to two variables (vara v varb), determine if we can assign True/False values to these variables so that the entire 2-SAT instance is evaluated to be true, i.e. satisfiable.
It turns out that each clause (a v b) can be turned into four vertices a, not a, b, and not b with two edges: (not a → b) and (not b → a). Thus we have a Directed Graph. If there is at least one variable and its negation inside an SCC of such graph, we know that it is impossible to satisfy the 2-SAT instance.
After such directed graph modeling, we can run an SCC finding algorithm (Kosaraju's or Tarjan's algorithm) to determine the satisfiability of the 2-SAT instance.
Quiz: Which Graph Traversal Algorithm is Better?
讨论:为什么?
e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
There are interesting questions about these two graph traversal algorithms: DFS+BFS and variants of graph traversal problems, please practice on Graph Traversal training module (no login is required, but short and of medium difficulty setting only).
However, for registered users, you should login and then go to the Main Training Page to officially clear this module and such achievement will be recorded in your user account.
We also have a few programming problems that somewhat requires the usage of DFS and/or BFS: Kattis - reachableroads and Kattis - breakingbad.
Try to solve them and then try the many more interesting twists/variants of this simple graph traversal problem and/or algorithm.
You are allowed to use/modify our implementation code for DFS/BFS Algorithms:
dfs_cc.cpp/bfs.cpp
dfs_cc.java/bfs.java
dfs_cc.py/bfs.py
dfs_cc.ml/bfs.ml
e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
e-Lecture: The content of this slide is hidden and only available for legitimate CS lecturer worldwide. Drop an email to visualgo.info at gmail dot com if you want to activate this CS lecturer-only feature and you are really a CS lecturer (show your University staff profile).
Return to 'Exploration Mode' to start exploring!
Note that if you notice any bug in this visualization or if you want to request for a new visualization feature, do not hesitate to drop an email to the project leader: Dr Steven Halim via his email address: stevenhalim at gmail dot com.
绘制图表
图示
深度优先搜索(s)
广度优先搜说(s)
拓扑排序
二分图检查
切断顶点/ 桥
SCC 算法
2-SAT 检查