查找有向图中所有的环

在对每个结点进行DFS的基础上进行了一些优化。

优化原理:若findCycle(0,e), 找到一个0-2-3的环,那么不再对2、3进行findCycle()函数。因为2或3若是构成有其它的环,findCycle(0)回溯到2或3时,会找出这些环。

 
 
 1 import java.util.*;
 2 
 3 public class GetAllCyclesForDirectedGraph{
 4 static List<Integer> trace;
 5 static Set<Integer> searched=new HashSet<>();
 6 static Set<List<Integer>> allCircles = new HashSet<>();
 7 
 8 public static void main(String[] args) {
 9  int n=7; 
10 int[][] e={ {0,1,1,0,0,0,0}, {0,0,0,1,0,0,0}, 
11             {0,0,0,0,0,1,0}, {0,0,0,0,1,0,0}, 
12             {0,0,1,0,0,0,0}, {0,0,0,0,1,0,1}, 
13             {1,0,1,0,0,0,0}};
14 for(int i=0;i<n;i++){
15 if(searched.contains(i)) 
16 continue;
17 trace =new ArrayList<>();
18 findCycle(i,e); 
20 }
21 
22 for(List<Integer> list:allCircles)
23 System.out.println("circle: "+list);
24 }
25 
26 
27 static void findCycle(int v, int[][]e){
28 int j=trace.indexOf(v); 
29 if(j!=-1) {

31 List<Integer> circle=new ArrayList<>(); 32 while(j<trace.size()) {

34 searched.add(trace.get(j)); 35 circle.add(trace.get(j)); 36 j++; 37 } 39 Collections.sort(circle); allCircles.add(circle); 42 return; 43 } 44 45 46 trace.add(v); 47 for(int i=0;i<e.length;i++) { 48 if(e[v][i]==1){ 49 findCycle(i,e); 50 } 51 } 52 trace.remove(trace.size()-1); 53 } 54 55 }
 
  
 
 

猜你喜欢

转载自www.cnblogs.com/black-fish/p/9246701.html