当前位置:   article > 正文

判断有向图图是否有环_判断有向图是否有环,若有环,则将环剔除java

判断有向图是否有环,若有环,则将环剔除java
  1. package Graph;
  2. import java.util.ArrayList;
  3. import java.util.LinkedList;
  4. import java.util.Scanner;
  5. import java.util.Stack;
  6. public class DirectedCycle {
  7. int v, e;
  8. boolean []visit;
  9. boolean []onStack;
  10. int []path;
  11. boolean hasCycle = false;
  12. int s;
  13. Stack<Integer> stack;
  14. LinkedList<Integer> []adj;
  15. public static void main(String[] args) {
  16. new DirectedCycle().run();
  17. }
  18. public void run() {
  19. Scanner in = new Scanner(System.in);
  20. v = in.nextInt();
  21. e = in.nextInt();
  22. visit = new boolean[v+1];
  23. onStack = new boolean[v+1];
  24. adj = new LinkedList[v+1];
  25. path = new int[v];
  26. stack = new Stack<>();
  27. for(int i = 0; i < v; i++ ) {
  28. adj[i] = new LinkedList<>();
  29. }
  30. for(int i = 0; i < e; i++ ) {
  31. int a = in.nextInt();
  32. int b = in.nextInt();
  33. adj[a].offer(b);
  34. }
  35. for(int i = 0; i < v; i++ ) {
  36. if(!visit[i])
  37. dfs(i);
  38. }
  39. if(hasCycle)
  40. printPath();
  41. else {
  42. System.out.println("No cycle!");
  43. }
  44. }
  45. public void printPath() {
  46. boolean flag = true;
  47. while(!stack.isEmpty()) {
  48. if(flag) {
  49. System.out.print(stack.pop());
  50. flag = false;
  51. }
  52. else
  53. System.out.print("-" + stack.pop());
  54. }
  55. }
  56. public void dfs(int cur) {
  57. visit[cur] = true;
  58. onStack[cur] = true;
  59. for(int w :adj[cur]) {
  60. if(!visit[w]) {
  61. path[w] = cur;
  62. dfs(w);
  63. }
  64. else if(onStack[w]) {
  65. hasCycle = true;
  66. stack.push(cur);//把结束点多入栈一次标记结束位置以区别与其他环
  67. for(int x = cur; x != w; x = path[x])//结束点为当前第一个出现的已标记并且在栈内的点
  68. stack.push(x);
  69. stack.push(w);
  70. return;
  71. }
  72. }
  73. onStack[cur] = false;
  74. }
  75. }



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

闽ICP备14008679号