其他分享
首页 > 其他分享> > 图论中环的判断

图论中环的判断

作者:互联网

无向图环的判断

def init();
def find(int x);//必须进行路径压缩
def merge(int x, int y);
if(find(x) == find(y) && G[x][y] != 0){ cycle = true;}
else merge(x,y);
public class Cycle {
     private boolean[] marked;
     private boolean hasCycle;
     public Cycle(Graph G) {       
         this.marked = new boolean[G.V()];
         this.hasCycle = false;
         for(int i=1; i<G.V(); i++) {
              if(!marked[i]) {
                  //默认第一个结点没有父节点
                  dfs(G, i, -1);
              }
         }
     }

     private void dfs(Graph G, int cur, int pre) {
         marked[cur] = true;
         for(Integer nxt : G.adj(cur)) {
              if(!marked[nxt]) {
                  dfs(G, nxt, cur);
              }
              else if(nxt != pre) {
                  this.hasCycle = true;
              }
         }
     }
     public boolean hasCycle() {return this.hasCycle;}

有向图环的判断

public class DiCycle {
     private boolean[] marked;//记录结点是否访问过
     private int[] edgeTo;//记录该结点的父节点
     private Stack<Integer> cycle;
     private boolean[] onStack;//记录当前访问路径上的结点
    
     public DiCycle(Digraph G) {
         marked = new boolean[G.V()];
         edgeTo  = new int[G.V()];
         cycle = new Stack<Integer>();
         onStack = new boolean[G.V()];
         for(int i=0; i<G.V(); i++) {
              if(!marked[i]) {
                  dfs(G, i);
              }
         }
     }
     private void dfs(Digraph G, int v) {
         // TODO Auto-generated method stub
         marked[v] = true;
         onStack[v] = true;
         for(Integer w : G.adj(v)) {
              if(this.hasCycle()) return ;
              else if(!marked[w]) {
                  edgeTo[w] = v;
                  dfs(G , w);
              }
              else if(onStack[w]) {
                  for(int x=v; x!=w; x=edgeTo[x]) {
                       cycle.push(x);
                  }
                  cycle.push(w); 
                  cycle.push(v);
              }
         }
         onStack[v] = false;//回溯时取消其在栈上,相当于清空栈,便于下一次dfs       
     }

     public void showCycle() {
         if(!this.hasCycle()) System.out.println("no cycle...");
         Stack<Integer> s = new Stack<Integer>();
         s = (Stack<Integer>) cycle.clone();
         while(!s.isEmpty()) {
              System.out.println(s.peek());
              s.pop();
          }
     }

标签:图论,判断,int,中环,结点,dfs,boolean,private,new
来源: https://www.cnblogs.com/czsharecode/p/10709715.html