圖論——環檢測
問題分析
檢測上圖是否有環其實也相當簡單,只要dfs的過程發現某個頂點的鄰接頂點已經訪問過了,就說明有環,除此之外,還要排除一種情況,如下:
例如從0開始dfs,0已訪問
dfs 1,發現1的鄰接頂點0已被訪問,此時不可以判定有環,即要排除已訪問的頂點不是上一個頂點(parent)
代碼
graph.txt
7 6
0 1
0 2
1 3
2 6
2 3
1 4
環檢測
public class CycleDetection2 {
private UndirectedGraph graph;
private boolean[] visited;
private boolean hasCycle;
public CycleDetection2(UndirectedGraph graph){
this.graph = graph;
visited = new boolean[graph.vertexNum()];
for(int v=0;v<graph.vertexNum();v++){
if(!visited[v]){
if(dfs(v,v)){
hasCycle = true;
break;
}
}
}
}
public boolean isHasCycle(){
return hasCycle;
}
/**
* v是從parent頂點過來的
* @param v
* @param parent
* @return
*/
private boolean dfs(int v,int parent){
visited[v] = true;
for(int w:graph.adj(v)) {
if(!visited[w]){
if(dfs(w,v))return true;
//0-----1,排除0->1->0這種環檢測
}else if(w!=parent){
return true;
}
}
return false;
}
public static void main(String[] args) {
UndirectedGraph graph = new UndirectedGraph("graph.txt");
System.out.println(graph);
CycleDetection2 graphDFS = new CycleDetection2(graph);
System.out.println(graphDFS.isHasCycle());
}
}
建圖代碼
public class UndirectedGraph {
private int V;//頂點數
private int E;//邊數
private TreeSet<Integer>[] adj;//鄰接表,TreeSet數組存儲
public UndirectedGraph(String filename){
File file = new File(filename);
try(Scanner scanner = new Scanner(file)){
V = scanner.nextInt();//頂點數
if(V<=0) throw new RuntimeException("頂點個數必須大於0");
adj = new TreeSet[V];
for(int i=0;i<V;i++){
adj[i] = new TreeSet<>();
}
E = scanner.nextInt();//邊數
if(E<0) throw new RuntimeException("邊數不能爲負數");
for(int i=0;i<E;i++){
int a = scanner.nextInt();
validateVertex(a);
int b = scanner.nextInt();
validateVertex(b);
//自環邊檢測
if(a==b){
throw new RuntimeException("簡單圖不能包含自環邊");
}
//平行邊檢測
if(adj[a].contains(b)){
throw new RuntimeException("簡單圖不能包含平行邊");
}
adj[a].add(b);
adj[b].add(a);
}
}catch (IOException e){
e.printStackTrace();
}
}
public void validateVertex(int v){
if(v<0||v>=V){
throw new RuntimeException("頂點下標溢出");
}
}
public int vertexNum(){
return V;
}
public int edgeNum(){
return E;
}
public boolean hasEdge(int v,int w){
validateVertex(v);
validateVertex(w);
return adj[v].contains(w);
}
//鄰接頂點
public Iterable<Integer> adj(int v){
validateVertex(v);
return adj[v];
}
//度
public int degree(int v){
validateVertex(v);
return adj[v].size();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("V = %d,E = %d\n",V,E));
for(int i=0;i<adj.length;i++){
sb.append(i+":");
for (Iterator<Integer> it = adj[i].iterator(); it.hasNext(); ) {
sb.append(it.next()+" ");
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
UndirectedGraph graph = new UndirectedGraph("graph.txt");
System.out.println(graph);
}
}