当前位置:   article > 正文

有向有环图两点间路径问题

有向有环图

有向有环图两点间路径问题

本文主要介绍有向有环图两点间的路径问题。先简要的看一下什么是有向有环图。

那么如何利用类似深度优先遍历的方式对1到7之间的路径进行查询呢,下面说一下思路。
1、首先需要把有向有环图经过破环,形成有向无环图。
2、利用深度优先遍历实现对有向无环图所有路径进行查找。

好,下面看一下具体的实现。
首先是一个辅助类
  1. package com.xueyou.graph;
  2. public class node {
  3. private int source;
  4. private int target;
  5. public int getSource() {
  6. return source;
  7. }
  8. public void setSource(int source) {
  9. this.source = source;
  10. }
  11. public int getTarget() {
  12. return target;
  13. }
  14. public void setTarget(int target) {
  15. this.target = target;
  16. }
  17. public node() {
  18. }
  19. public node(int source, int target) {
  20. this.source = source;
  21. this.target = target;
  22. }
  23. }

然后是具体的递归实现
  1. package com.xueyou.graph;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class demo {
  5. public static void main(String[] args) {
  6. List<node> nodeList = new ArrayList<>();
  7. node node = new node(1, 2);
  8. node node2 = new node(1, 6);
  9. node node3 = new node(2, 4);
  10. node node4 = new node(2, 5);
  11. node node7 = new node(4, 3);
  12. node node1 = new node(1, 4);
  13. node node8 = new node(5, 7);
  14. node node9 = new node(6, 7);
  15. node node6 = new node(3, 7);
  16. node node5 = new node(3, 2);
  17. nodeList.add(node);
  18. nodeList.add(node1);
  19. nodeList.add(node2);
  20. nodeList.add(node3);
  21. nodeList.add(node4);
  22. nodeList.add(node5);
  23. nodeList.add(node6);
  24. nodeList.add(node7);
  25. nodeList.add(node8);
  26. nodeList.add(node9);
  27. List<Integer> ints = new ArrayList<>();
  28. findpath(nodeList, 1, 7, ints);
  29. }
  30. public static void findpath(List<node> nodeList, int source, int target, List<Integer> path) {
  31. System.out.println(path);
  32. if (path.indexOf(source) > -1) {
  33. return;
  34. }
  35. path = cleanMutilPath(path);
  36. for (int i = 0; i < nodeList.size(); i++) {
  37. node node = nodeList.get(i);
  38. if (node.getSource() == source) {
  39. //如果相等则找到路径
  40. if (node.getTarget() == target) {
  41. path.add(node.getSource());
  42. path.add(node.getTarget());
  43. List<Integer> tmpList = new ArrayList<>();
  44. tmpList = cleanMutilPath(path);
  45. System.out.println("find path origin:" + path);
  46. System.out.println("find path clean:" + tmpList);
  47. path.clear();
  48. return;
  49. }
  50. path.add(node.getSource());
  51. findpath(nodeList, node.getTarget(), target, path);
  52. }
  53. }
  54. }
  55. public static List<Integer> cleanMutilPath(List<Integer> path) {
  56. List<Integer> tmp = new ArrayList<>();
  57. for (Integer integer : path) {
  58. if (tmp.indexOf(integer) < 0) {
  59. tmp.add(integer);
  60. }
  61. }
  62. return tmp;
  63. }
  64. }

下面是运行结果:



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/874046
推荐阅读
相关标签
  

闽ICP备14008679号