數據結構系列是我學習做的筆記,會持續更新,源碼分享在github:數據結構,當然你也可以從下面的代碼片中獲取
注:github代碼更新會有延遲,關注不迷路😄
圖的遍歷應用舉例3
題目:編程實現應用深度優先搜索策略判斷一個有向圖是否存在環
其中,涉及到:接口 IGraph 和類 ALGraph 詳見博文圖的存儲結構之鄰接表
當然也可以訪問我的github,獲取完整項目代碼(注:更新有延遲),地址見博文開頭
package code.Graph;
import code.Stack.LinkStack;
/**
* 圖的遍歷方法應用舉例3
*
* 題目:
* 編程實現應用深度優先搜索策略判斷一個有向圖是否存在環
* */
public class GraphSearchExample3 {
private boolean [] visited; //訪問標誌數組
//按照深度優先搜索訪問的先後順序記錄在一個連通分支當中的頂點元素
private LinkStack S = new LinkStack();
private boolean find = false; //記錄是否已經找到了環
public void findCircle(IGraph G)throws Exception{
visited = new boolean[G.getVexNum()];
for (int w = 0;w<G.getVexNum();w++){
//訪問數組初始化
visited[w] = false;
}
for (int v = 0;v<G.getVexNum();v++){
if (!visited[v]){ //對尚未訪問的頂點調用DFS
findDFS(G,v);
}
}
if (find){
System.out.println("此圖存在環");
}else {
System.out.println("此圖不存在環!");
}
}
public void findDFS(IGraph G,int v)throws Exception{
if (!find){
visited[v] = true;
S.push(v);
for (int w = G.firstAdjVex(v);w>=0;w = G.nextAdjVex(v,w)){
if (visited[w]&&isDuplicate(w)){
find = true;
}else {
//對v尚未訪問的鄰接頂點w遞歸調用DFS
findDFS(G,w);
}
}
S.pop();
}
}
/**
* 判斷棧S中是否存在值爲w的數據元素
* */
private boolean isDuplicate(Integer w)throws Exception{
LinkStack S1 = new LinkStack(); //輔助棧
while (!S.isEmpty()&&!((Integer)S.peek()).equals(w)){
//利用輔助棧S1記錄出棧的數據元素
S1.push(S.pop());
}
if (S.isEmpty()){ //重新把數據元素放入棧S中
while (!S1.isEmpty()){
S.push(S1.pop());
}
return false;
}else {
return true;
}
}
public static ALGraph getGraphSearch_G(){
/*
* 構建一個有向圖
* 其中:
*
* A--->B--->C--->D--->E-->F--->A
*
* F--->B--->E
*
* */
ArcNode ab = new ArcNode(1);
VNode A = new VNode("A",ab);
ArcNode bc = new ArcNode(2);
ArcNode be = new ArcNode(4,0,bc);
VNode B = new VNode("B",be);
ArcNode cd = new ArcNode(3);
VNode C = new VNode("C",cd);
ArcNode de = new ArcNode(4);
VNode D = new VNode("D",de);
ArcNode ef = new ArcNode(5);
VNode E = new VNode("E",ef);
ArcNode fa = new ArcNode(0);
ArcNode fb = new ArcNode(1,0,fa);
VNode F = new VNode("F",fb);
VNode [] vexs = {A,B,C,D,E,F};
return new ALGraph(GraphKind.DG,6,8,vexs);
}
public static void main(String [] args)throws Exception{
GraphSearchExample3 test = new GraphSearchExample3();
test.findCircle(GraphSearchExample3.getGraphSearch_G());
}
}