1. 程式人生 > >查找有向圖中所有的環

查找有向圖中所有的環

while rem hashset AR i++ nta str for graph

在對每個結點進行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 }

 

查找有向圖中所有的環