图的深度优先遍历

所谓图的遍历就是按照某种顺序访问图中所有的节点,根据访问的顺序不同,可以分为两类:

  • 深度优先遍历
  • 广度优先遍历

在本节中讲解深度优先遍历。

所谓深度优先遍历(Depth First Search,简称 DFS),是指在遍历时,尽可能深的访问图的节点。为了更好的理解图的深度优先遍历,我们先看看树的深度优先遍历,与图的深度优先遍历一样,树的深度优先遍历也是指尽可能深的访问树的节点,也就是说如果一个节点有孩子节点,那么我们下一步就应该遍历它的孩子节点(深度),如下

图的深度优先遍历 - 图1

从上面的动图可以看出,当我们遍历完当前节点以后,如果该节点有孩子节点,那么接下来我们去遍历孩子节点,我们的遍历策略就是尽可能深的遍历。类比于图,对于图来说,如果一个图的节点有邻接节点,那么在遍历完该节点后,我们下一步就去遍历它的邻接节点

图的深度优先遍历 - 图2

这就是图的深度优先遍历,上图深度优先遍历访问的顺序是 图的深度优先遍历 - 图3,我们将在下面的编程中验证是否正确。

图的遍历与树的遍历有一处不同,那就是重复访问问题。树不会发生重复访问的问题,这是因为树的节点只能通过父节点访问到,只有一种路径到达该节点,所以我们不必担心;但是对于图来说,一个图中的节点可以与多个节点进行连接,这就意味着有多种路径到达该节点,这就会导致某节点已经通过一个相邻的节点被访问,但是它还是有可能通过别的相邻节点再次被访问。

所以我们需要通过一个标志来表示某个图的节点是否已经被访问过了,如果已经被访问过了,那么我们就不能再次访问,我们通过一个 visited 数组来表示图中的某个节点是否已经被访问过了,visited 数组是一个 boolean 类型的数组,值为 true 时就表示该节点已经被访问过了,例如 visited[0] = true 就表示节点 0 已经被访问过了。

下面我就将编程具体实现:

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class DFSGraph {
  4. // 图的表示中定义的 Graph 接口
  5. private Graph graph;
  6. // 保存深度优先遍历的顺序
  7. private ArrayList<Integer> order;
  8. // 保存节点是否已经被访问过
  9. private boolean[] visited;
  10. public DFSGraph(Graph graph) {
  11. this.graph = graph;
  12. order = new ArrayList<>(graph.V());
  13. // 初始化 visited 中的元素值为 false
  14. visited = new boolean[graph.V()];
  15. Arrays.fill(visited, false);
  16. }
  17. // DFS 的实现,首先从节点 0 开始遍历
  18. public void dfs() {
  19. dfs(0);
  20. }
  21. private void dfs(int v) {
  22. // 标记当前节点为访问过的状态
  23. visited[v] = true;
  24. // 向 order 中添加当前节点
  25. order.add(v);
  26. for (int w: graph.adj(v)) {
  27. // 如果邻接节点没有被访问过,那么遍历该邻接节点
  28. if (!visited[w]) {
  29. dfs(w);
  30. }
  31. }
  32. }
  33. public Iterable<Integer> order() {
  34. return order;
  35. }
  36. public static void main(String[] args) {
  37. // 使用邻接表表示图
  38. Graph graph = new AdjSet("g.txt");
  39. // 实例化一个 DFSGraph
  40. DFSGraph dfsGraph = new DFSGraph(graph);
  41. // 调用 dfs 方法进行深度优先遍历
  42. dfsGraph.dfs();
  43. // 打印出深度优先遍历的顺序
  44. System.out.println(dfsGraph.order());
  45. }
  46. }

其中 g.txt 的内容如下

  1. 6 5
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 4
  6. 2 5

这个文件表示的图与我们在上面的动图中看到的图是一样的,我们来看下打印的结果

  1. [0, 1, 3, 2, 4, 5]

这与我们在动图中看到的遍历顺序是一致的。

但是上面我们实现的深度优先遍历有一个小 bug,那就是上面的深度优先遍历只适合只有一个联通分量的图,如果有多个联通分量,那么其他联通分量中的节点就永远不可能被访问到,如

图的深度优先遍历 - 图4

既然图中有节点永远不会被访问到,那么还能叫图的遍历吗,图的遍历可是要求能够访问图中所有的节点的,所以我们对代码进行改进

图的深度优先遍历 - 图5

这次我们不只是从节点 图的深度优先遍历 - 图6 开始遍历,在遍历完节点 图的深度优先遍历 - 图7 所在的联通分量以后,我们检查是否还有节点没有遍历,即是否存在别的联通分量,如果有,那么我们还有遍历该节点所在的联通分量。

在最后我们进行一个扩展,我们知道树的深度优先遍历分为三种

  • 前序遍历
  • 中序遍历
  • 后序遍历

图没有中序遍历,它分为两种

  • 深度优先前序遍历
  • 深度优先后序遍历

刚刚我们所编程的只是图的深度优先前序遍历,现在我们不妨写一下后序遍历的代码。在写代码之前,我们先明确后序遍历的这个后指的是什么,这个后在树的遍历中指的是先访问当前节点的孩子节点,然后访问当前节点,也就是访问当前节点在访问当前节点的孩子节点之后。类比于图,这个后指的就是先访问当前节点的邻接节点,然后再访问当前节

图的深度优先遍历 - 图8

上面后序遍历的顺序为 图的深度优先遍历 - 图9,我们重构一下上面的代码,我们使用 preorder 来保存前序遍历的结果,使用 postorder 来保存后序遍历的结果:

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. public class DFSGraph {
  4. private Graph graph;
  5. private ArrayList<Integer> preorder;
  6. private ArrayList<Integer> postorder;
  7. private boolean[] visited;
  8. public DFSGraph(Graph graph) {
  9. this.graph = graph;
  10. preorder = new ArrayList<>(graph.V());
  11. postorder = new ArrayList<>(graph.V());
  12. visited = new boolean[graph.V()];
  13. Arrays.fill(visited, false);
  14. }
  15. public void dfs() {
  16. for (int i = 0; i < visited.length; i++) {
  17. if (!visited[i]) {
  18. dfs(i);
  19. }
  20. }
  21. }
  22. private void dfs(int v) {
  23. visited[v] = true;
  24. // 前序遍历:在遍历相邻节点前,遍历当前节点
  25. preorder.add(v);
  26. for (int w: graph.adj(v)) {
  27. if (!visited[w]) {
  28. dfs(w);
  29. }
  30. }
  31. // 后序遍历:遍历相邻节点后,再遍历当前节点
  32. postorder.add(v);
  33. }
  34. public Iterable<Integer> preorder() {
  35. return preorder;
  36. }
  37. public Iterable<Integer> postorder() {
  38. return postorder;
  39. }
  40. public static void main(String[] args) {
  41. Graph graph = new AdjSet("g.txt");
  42. DFSGraph dfsGraph = new DFSGraph(graph);
  43. dfsGraph.dfs();
  44. System.out.println(dfsGraph.postorder());
  45. }
  46. }

打印的结果为

  1. [3, 1, 4, 5, 2, 0]

深度优先遍历的应用

联通分量

第一个问题是如何求解图中有多少个联通分量。其实这个问题非常的简单,在上面的我们修改 DFS 的小 bug 时就提到,因为有多个联通分量,我们无法遍历完所有图中的节点,所以我们修改了代码

图的深度优先遍历 - 图10

每次当我们在 for 循环中调用一次 dfs 的时候,就说明存在一个联通分量(Connected Component),所以我们只要在调用 dfs 时统计联通分量的个数就可以,我们使用一个成员变量 ccount 来保存联通分量的个数

  1. import java.util.Arrays;
  2. public class CCGraph {
  3. private int cccount;
  4. private Graph graph;
  5. private boolean[] visited;
  6. public CCGraph(Graph graph) {
  7. this.graph = graph;
  8. this.cccount = 0;
  9. visited = new boolean[graph.V()];
  10. Arrays.fill(visited, false);
  11. }
  12. public void dfs() {
  13. for (int i = 0; i < visited.length; i++) {
  14. if (!visited[i]) {
  15. // 联通分量个数增加
  16. cccount++;
  17. dfs(i);
  18. }
  19. }
  20. }
  21. private void dfs(int v) {
  22. visited[v] = true;
  23. for (int w: graph.adj(v)) {
  24. if (!visited[w]) {
  25. dfs(w);
  26. }
  27. }
  28. }
  29. public int getCccount() {
  30. return cccount;
  31. }
  32. public static void main(String[] args) {
  33. Graph graph = new AdjSet("g.txt");
  34. CCGraph ccGraph = new CCGraph(graph);
  35. ccGraph.dfs();
  36. int cccount = ccGraph.getCccount();
  37. System.out.println(cccount); // 2
  38. }
  39. }

上面的代码与 DFSGraph 类的代码几乎是一致的,只不过统计了联通分量的个数。g.txt 中的内容为:

  1. 7 6
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 5
  6. 2 4
  7. 4 5

对于的图的形状如下:

图的深度优先遍历 - 图11

可见上面的图有两个联通分量。

第二个与联通分量有关的问题是,我们希望得到每个联通分量中有多少个节点,以及分别包含哪些节点,我们可以使用一个 ArrayList 数组保存每个联通分量包含的节点,修改 dfs 如下

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. @SuppressWarnings("all")
  4. public class CCGraph {
  5. private int cccount;
  6. private Graph graph;
  7. private boolean[] visited;
  8. // 为什么不使用数组? 因为数组需要事先开辟空间,而我们事先不知道有多少个联通分量
  9. private ArrayList<ArrayList<Integer>> lists;
  10. // 构造函数对成员变量进行初始化
  11. public CCGraph(Graph graph) {
  12. this.graph = graph;
  13. this.cccount = 0;
  14. visited = new boolean[graph.V()];
  15. Arrays.fill(visited, false);
  16. lists = new ArrayList<>();
  17. }
  18. public void dfs() {
  19. for (int i = 0; i < visited.length; i++) {
  20. if (!visited[i]) {
  21. cccount++;
  22. // 每增加一个联通分量,新建一个 list 来保存该联通分量中包含的节点
  23. ArrayList<Integer> list = new ArrayList<>();
  24. lists.add(list);
  25. dfs(i, list);
  26. }
  27. }
  28. }
  29. private void dfs(int v, ArrayList<Integer> list) {
  30. visited[v] = true;
  31. // 将节点保存在所在联通分量对应的 list 中
  32. list.add(v);
  33. for (int w: graph.adj(v)) {
  34. if (!visited[w]) {
  35. dfs(w, list);
  36. }
  37. }
  38. }
  39. public int getCCcount() {
  40. return cccount;
  41. }
  42. public ArrayList<ArrayList<Integer>> getCCList() {
  43. return lists;
  44. }
  45. // 判断两个节点是否在同一个联通分量中(是否连接)
  46. public boolean isConnected(int v, int w) {
  47. for (int i = 0; i < cccount; i++) {
  48. ArrayList list = lists.get(i);
  49. // 某联通分量中是否同时包含这两个节点
  50. if (list.contains(v) && list.contains(w)) {
  51. return true;
  52. }
  53. }
  54. // 所有的联通分量都不同时包含这两个节点,说明这两个节点不在同一个联通分量中
  55. return false;
  56. }
  57. public static void main(String[] args) {
  58. Graph graph = new AdjSet("g.txt");
  59. CCGraph ccGraph = new CCGraph(graph);
  60. ccGraph.dfs();
  61. int cccount = ccGraph.getCCcount();
  62. System.out.println(cccount); // 2
  63. // 打印出联通分量
  64. ArrayList<ArrayList<Integer>> lists = ccGraph.getCCList();
  65. for (int i = 0; i < cccount; i++) {
  66. // 获得每个联通分量对应的 list,里面保存了该联通分量包含的节点
  67. ArrayList<Integer> list = lists.get(i);
  68. // 打印出联通分量中包含的节点
  69. System.out.print(i + ": ");
  70. for (int v: list) {
  71. System.out.print(v + " ");
  72. }
  73. System.out.println();
  74. }
  75. System.out.println(ccGraph.isConnected(0, 5)); // true
  76. System.out.println(ccGraph.isConnected(0, 6)); // false
  77. }
  78. }

上述的打印结果为

  1. 2
  2. 0: 0 1 3 2 4 5
  3. 1: 6
  4. true
  5. false

路径问题

所谓的路径问题就是求两个节点之间是否有路径,这个问题很简单,直接使用我们上面的 isConnected 方法就可以知道两个节点之间是否有路径了。不过我们更想知道的是,两个节点之间的路径是什么,即一个节点到达另一个节点会经历哪些节点。

对于下面的一幅图,我们想知道从节点 图的深度优先遍历 - 图12 到节点 图的深度优先遍历 - 图13 之间的路径

图的深度优先遍历 - 图14

我们需要记录遍历时当前节点的前一个节点,例如遍历节点 图的深度优先遍历 - 图15 后会接着遍历节点 图的深度优先遍历 - 图16,那么节点 图的深度优先遍历 - 图17 的前一个节点就是 图的深度优先遍历 - 图18,通过这些信息就可以知道两个节点之间具体的路径。首先使用 DFS 图,在遍历的过程中记录信息,如下

图的深度优先遍历 - 图19

在上面我们从节点 图的深度优先遍历 - 图20 开始遍历,在遍历的过程中我们记录了当前节点之前的节点,最后得到这么一个结果

图的深度优先遍历 - 图21

现在我们想知道节点 图的深度优先遍历 - 图22 是如何到达节点 图的深度优先遍历 - 图23 的,直接逆推就可以知道路径为 图的深度优先遍历 - 图24,如下

图的深度优先遍历 - 图25

这个算法可以求得节点 图的深度优先遍历 - 图26 与任何一个节点之间的路径,但是不能求得任意两点之间的路径,因为我们是从节点 图的深度优先遍历 - 图27 开始遍历的,如果我们想求得节点 图的深度优先遍历 - 图28 与节点 图的深度优先遍历 - 图29 之间的路径,那么我们需要从节点 图的深度优先遍历 - 图30 开始遍历,所以我们这种算法只能求解单源路径(Single Source Path) 问题。

在编程实现方面,我们使用一个 pre 数组来保存当前节点的前一个节点,例如,pre[3] = 1 就表示节点 图的深度优先遍历 - 图31 的前一个节点是节点 图的深度优先遍历 - 图32

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Collections;
  4. public class SingleSourcePath {
  5. private Graph graph;
  6. private boolean[] visited;
  7. private int[] pre;
  8. // 从节点 s 开始遍历
  9. private int s;
  10. public SingleSourcePath(Graph graph, int s) {
  11. this.graph = graph;
  12. this.s = s;
  13. visited = new boolean[graph.V()];
  14. Arrays.fill(visited, false);
  15. pre = new int[graph.V()];
  16. Arrays.fill(pre, -1);
  17. // 默认认为源的前一个节点为自己,这个值访问不到,可以是任何值
  18. dfs(s, s);
  19. }
  20. private void dfs(int v, int parent) {
  21. visited[v] = true;
  22. pre[v] = parent;
  23. for (int w: graph.adj(v)) {
  24. if (!visited[w]) {
  25. dfs(w, v);
  26. }
  27. }
  28. }
  29. public boolean isConnected(int t) {
  30. // 如果 pre[t] != -1,说明遍历到了该节点,则该节点与源节点是联通的
  31. return pre[t] != -1;
  32. }
  33. public Iterable<Integer> path(int t) {
  34. ArrayList<Integer> path = new ArrayList<>();
  35. // 如果不是联通的,直接返回
  36. if (!isConnected(t)) return path;
  37. int cur = t;
  38. while (cur != s) {
  39. path.add(cur);
  40. cur = pre[cur];
  41. }
  42. path.add(s);
  43. Collections.reverse(path);
  44. return path;
  45. }
  46. public static void main(String[] args) {
  47. Graph graph = new AdjSet("g.txt");
  48. SingleSourcePath singleSourcePath = new SingleSourcePath(graph, 0);
  49. System.out.println(singleSourcePath.path(5));
  50. }
  51. }

其中 g.txt

  1. 7 6
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 5
  6. 2 4
  7. 4 5

对应的图就是上面的动图,输出为

  1. [0, 2, 4, 5]

假设现在我们只想求源点 图的深度优先遍历 - 图33 到点 图的深度优先遍历 - 图34 之间的路径,而不是 图的深度优先遍历 - 图35 到任意一个点的路径,很明显我们的要求降低了,这意味着我们记录的信息更少,那我们算法可不可以加快呢?

当然可以,在上面我们求解源点 图的深度优先遍历 - 图36 到任意一点的路径,所以需要对源点 图的深度优先遍历 - 图37 所在的联通分量做 图的深度优先遍历 - 图38,需要遍历联通分量中所有的节点,但是现在我们只需要求解到固定点 图的深度优先遍历 - 图39 的路径,我们不需要完整的做一遍 图的深度优先遍历 - 图40,当我们遍历到节点 图的深度优先遍历 - 图41 时,就已经可以退出遍历了,提前终止遍历可以获得更快的性能。

假设我们需要求解源点 图的深度优先遍历 - 图42 到节点 图的深度优先遍历 - 图43 的路径

图的深度优先遍历 - 图44

在编码上,在我们在设计 dfs 函数时,我们需要返回一个布尔值,代表是否已经找到节点 图的深度优先遍历 - 图45,如果已经找到,我们就不需要做后续的遍历了,直接终止遍历

  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.Collections;
  4. public class Path {
  5. private Graph graph;
  6. private boolean[] visited;
  7. private int[] pre;
  8. private int s;
  9. private int t;
  10. public Path(Graph graph, int s, int t) {
  11. this.graph = graph;
  12. this.s = s;
  13. this.t = t;
  14. visited = new boolean[graph.V()];
  15. Arrays.fill(visited, false);
  16. pre = new int[graph.V()];
  17. Arrays.fill(pre, -1);
  18. dfs(s, s);
  19. }
  20. private boolean dfs(int v, int parent) {
  21. visited[v] = true;
  22. pre[v] = parent;
  23. // 如果已经找到,直接返回,不再继续遍历
  24. if (v == t) {
  25. return true;
  26. }
  27. for (int w: graph.adj(v)) {
  28. if (!visited[w]) {
  29. // 如果在某相邻节点的深度优先遍历中找到节点 t,不再继续遍历其他相邻节点,提前返回
  30. if (dfs(w, v)) {
  31. return true;
  32. }
  33. }
  34. }
  35. return false;
  36. }
  37. public boolean isConnected() {
  38. return visited[t];
  39. }
  40. public Iterable<Integer> path() {
  41. ArrayList<Integer> path = new ArrayList<>();
  42. if (!isConnected()) {
  43. return path;
  44. }
  45. int cur = t;
  46. while (cur != s) {
  47. path.add(cur);
  48. cur = pre[cur];
  49. }
  50. path.add(s);
  51. Collections.reverse(path);
  52. return path;
  53. }
  54. public static void main(String[] args) {
  55. Graph graph = new AdjSet("g.txt");
  56. Path path = new Path(graph, 0, 3);
  57. System.out.println(Arrays.toString(path.visited));
  58. System.out.println(path.path());
  59. }
  60. }

输出为

  1. [true, true, false, true, false, false, false]
  2. [0, 1, 3]

从打印结果可以看出,我们并没有遍历所有的节点,这样提前终止遍历可以提高查找的速度。

无向图的环检测

我们怎么判断一幅图有没有环呢? 很简单,我们使用深度优先遍历,当访问到某节点时,如果该节点的某邻接节点已经被访问过,并且该邻接节点不是它的上一个节点,那么就说明该图中包含一个环

图的深度优先遍历 - 图46

明白这一点以后我们就可以编写代码了

  1. import java.util.Arrays;
  2. public class CircleDetection {
  3. private Graph graph;
  4. private boolean[] visited;
  5. private boolean hasCircle;
  6. public CircleDetection(Graph graph) {
  7. this.graph = graph;
  8. visited = new boolean[graph.V()];
  9. Arrays.fill(visited, false);
  10. hasCircle = false;
  11. }
  12. public void dfs() {
  13. // 任一联通分量中有环,那么图中就有环
  14. for (int i = 0; i < visited.length; i++) {
  15. if (!visited[i]) {
  16. dfs(i, i);
  17. }
  18. }
  19. }
  20. private void dfs(int v, int parent) {
  21. visited[v] = true;
  22. for (int w: graph.adj(v)) {
  23. if (!visited[w]) {
  24. dfs(w, v);
  25. // 进入下面的 if 判断就说明 w 已经访问过了
  26. // 如果 w 不是它的上一个节点,说明有环
  27. } else if (w != parent){
  28. hasCircle = true;
  29. }
  30. }
  31. }
  32. public boolean hasCircle() {
  33. return this.hasCircle;
  34. }
  35. public static void main(String[] args) {
  36. Graph graph = new AdjSet("g.txt");
  37. CircleDetection circleDetection = new CircleDetection(graph);
  38. circleDetection.dfs();
  39. System.out.println(circleDetection.hasCircle()); // true
  40. }
  41. }

其中 g.txt 的内容如下

  1. 7 6
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 5
  6. 2 4
  7. 4 5

所对应的图如下

图的深度优先遍历 - 图47

如果我们将节点 图的深度优先遍历 - 图48图的深度优先遍历 - 图49 之间的边断开,那么图中是没有环的,新建 g2.txt 如下

  1. 7 5
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 4
  6. 4 5
  1. Graph graph2 = new AdjSet("g2.txt");
  2. CircleDetection circleDetection2 = new CircleDetection(graph2);
  3. circleDetection2.dfs();
  4. System.out.println(circleDetection2.hasCircle()); // false

另外,我们可以提前返回进行优化,如果我们已经找到了环,那么我们可以提前终止,后面就不需要继续查找了,我们修改 dfs 的返回值为 boolean 类型,这时 dfs 函数的含义就是从顶点 图的深度优先遍历 - 图50 开始,判断图中是否有环

  1. public void dfs() {
  2. for (int i = 0; i < visited.length; i++) {
  3. if (!visited[i]) {
  4. if (dfs(i, i)) {
  5. hasCircle = true;
  6. // 不用查找其他联通分量了
  7. break;
  8. }
  9. }
  10. }
  11. }
  12. private boolean dfs(int v, int parent) {
  13. visited[v] = true;
  14. for (int w: graph.adj(v)) {
  15. if (!visited[w]) {
  16. if (dfs(w, v)) {
  17. // 如果已经在某相邻节点中找到环,不用再遍历其他的相邻节点
  18. return true;
  19. }
  20. } else if (w != parent){
  21. // 如果已经找到环,不用继续向后遍历
  22. return true;
  23. }
  24. }
  25. return false;
  26. }

二分图检测

在这个小节我们来看一个二分图检测的问题,那么问题来了,什么叫二分图呢?

图的深度优先遍历 - 图51

二分图需要满足一下两个特点:

  1. 图中的节点被划分为两部分
  2. 图中的边连接的是两个部分的节点

在上图中,节点 图的深度优先遍历 - 图52 是一部分,节点 图的深度优先遍历 - 图53 是一部分,两部分的节点我使用不同的颜色进行填充;且图中所有的边都连接的是两个部分的节点。很明显上面的图满足二分图的两个特点,所以上面的图是一个二分图,那接下来的问题是如何检测一个图是否是一个二分图呢?

首先明白下面两个图是等价的

图的深度优先遍历 - 图54

但是我们很难从右边的图中分辨出两部分的节点。

解决这个问题的关键是图中的所有边连接的是两个不同部分的节点,如果我们将对图进行深度优先遍历的过程中对节点染色,相同部分的节点染为一个颜色,因为所有的边都连接的是不同部分的节点,这意味着任意节点的邻接节点的颜色和自己都是不同的。

我们在遍历时将所有邻接节点的颜色染为和自己不一样,但是如果邻接节点已经染色,并且染的颜色和自己相同,与二分图的定义冲突,那么说明不是一个二分图,反之邻接节点染的颜色和自己不同,则继续遍历,如果遍历完整个图时都没有冲突,那么说明这个图就是一个二分图

图的深度优先遍历 - 图55

代码如下:

  1. import java.util.Arrays;
  2. public class BinaryPartitionDetection {
  3. private Graph graph;
  4. private boolean[] visited;
  5. // 以 0 1 表示不同颜色
  6. private int[] colors;
  7. // 表示该图是否为二分图
  8. private boolean isBipartite;
  9. public BinaryPartitionDetection(Graph graph) {
  10. this.graph = graph;
  11. visited = new boolean[graph.V()];
  12. Arrays.fill(visited, false);
  13. // 初始化 colors 为 -1,表示未染色
  14. colors = new int[graph.V()];
  15. Arrays.fill(colors, -1);
  16. isBipartite = true;
  17. }
  18. public void dfs() {
  19. for (int i = 0; i < visited.length; i++) {
  20. if (!visited[i]) {
  21. // 如果在某联通分量中检测到不是二分图,不需要检测其他联通分量
  22. if (!dfs(i, 0)) {
  23. isBipartite = false;
  24. break;
  25. }
  26. }
  27. }
  28. }
  29. private boolean dfs(int v, int color) {
  30. visited[v] = true;
  31. // 染色
  32. colors[v] = color;
  33. for (int w: graph.adj(v)) {
  34. if (!visited[w]) {
  35. // 0 => 1 - color = 1
  36. // 1 => 1 - color = 0
  37. // 如果已经在遍历某邻接节点的过程中检测到不是二分图,不需要遍历其他邻接节点
  38. if (!dfs(w, 1 - color)) {
  39. return false;
  40. }
  41. // 进入 else if 表示该节点已经被访问过
  42. // 如果该节点的颜色与它的邻接节点相同,说明不是二分图,后面节点无需遍历
  43. } else if (colors[v] == colors[w]) {
  44. return false;
  45. }
  46. }
  47. return true;
  48. }
  49. public boolean isBipartite() {
  50. return isBipartite;
  51. }
  52. public static void main(String[] args) {
  53. Graph graph = new AdjSet("g3.txt");
  54. BinaryPartitionDetection binaryPartitionDetection = new BinaryPartitionDetection(graph);
  55. binaryPartitionDetection.dfs();
  56. System.out.println(binaryPartitionDetection.isBipartite()); // true
  57. }
  58. }

其中 g3.txt 的内容如下

  1. 7 6
  2. 0 1
  3. 0 2
  4. 1 3
  5. 2 4
  6. 2 5
  7. 4 6

所表示的图如下,与动图中的图相同

图的深度优先遍历 - 图56

在上面的实现中也使用了提前终止的技术,使用该技术可以很方便的提前终止遍历,提高程序的性能。