1. 程式人生 > >Expm 9_1 有向圖中環的判斷問題

Expm 9_1 有向圖中環的判斷問題

public 結點 搜索 分享圖片 pan F12 使用 stat org

【問題描述】

給定一個有向圖,要求使用深度優先搜索策略,判斷圖中是否存在環。

技術分享圖片
 1 package org.xiu68.exp.exp9;
 2 
 3 public class Exp9_1 {
 4 
 5     //用深度優先搜索判斷圖中是否存在環
 6     public static void main(String[] args) {
 7         // TODO Auto-generated method stub
 8         int[][] graph=new int[][]{
 9             {0,1,1,0},
10             {0,0,0,1},
11 {0,0,0,1}, 12 {0,0,0,0} 13 }; 14 checkCircle(graph,4); 15 16 int[][] graph1=new int[][]{ 17 {0,1,1,0}, 18 {0,0,0,1}, 19 {0,0,0,1}, 20 {1,0,0,0} 21 }; 22 checkCircle(graph1,4); 23 } 24 25
public static void checkCircle(int[][] graph,int vexNum){ 26 //boolean[] visited=new boolean[vex.length]; 27 28 //每一個結點有3種狀態,若為-1,則表示沒訪問過,若為0,則表示其後代結點正在被訪問中 29 //若為1表示結點已經訪問完成 30 int[] color=new int[vexNum]; 31 for(int i=0;i<color.length;i++) 32 color[i]=-1;
33 DFS(graph,0,color); 34 35 } 36 37 public static void DFS(int[][] graph,int v,int[] color){ 38 if(color[v]==0){ //存在環 39 System.out.println("圖中存在環"); 40 return; 41 }else if(color[v]==-1){ //沒搜索到該結點 42 color[v]=0; //記錄為正在搜索中 43 for(int i=0;i<color.length;i++){ 44 if(graph[v][i]==1) 45 DFS(graph,i,color); 46 } 47 color[v]=1; //結點v搜索完畢 48 } 49 } 50 51 }
View Code

Expm 9_1 有向圖中環的判斷問題