【alg4-無環圖】使用深度優先搜尋檢測環
阿新 • • 發佈:2020-12-10
程式碼
其中圖用到了Graph:
package section4_1;
public class Cycle {
private boolean[] marked;
private boolean hasCycle;
public Cycle(Graph G) {
marked = new boolean[G.V()];
for (int s = 0;s < G.V();s++) {
if (!marked[s]) {
dfs(G,s,s) ;
}
}
}
private void dfs(Graph G,int v, int u) {
marked[v] = true;
for (int w : G.adj(v)) {
if (!marked[w]) dfs(G,w,v);//將一個結點和它的鄰接結點繼續遞迴
else if (w != u) hasCycle = true;//如果已經訪問過的鄰接結點的鄰接結點不是該結點,則說明有環。
}
}
public boolean hasCycle() {
return hasCycle;
}
public static void main(String[] args) {
//有環圖
int[][] data1 = {
{0,5},
{2,4},
{2,3},
{1,2},
{0,1},
{3,4},
{3,5},
{ 0,2}
};
int vn = 6;
int e = 8;
Graph graph1 = new Graph(vn,e,data1);
Cycle cycle1 = new Cycle(graph1);
System.out.println(cycle1.hasCycle());
//無環圖
int[][] data2 = {
{0,1},
{0,2},
{0,3}
};
int vn2 = 4;
int e2 = 3;
Graph graph2 = new Graph(vn2,e2,data2);
Cycle cycle2 = new Cycle(graph2);
System.out.println(cycle2.hasCycle());
}
}