原理 就是判断图是否具有反向边 DFS每个点都是有父节点延伸过来的,如果寻找某个子节点的临接点时候发现 除了父节点被标记外还有其它被标记的节点和其相连,则必然有环。
package Graph;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class HasCycle {
boolean []visit;
boolean isHasCycle = false;//初始为无环
LinkedList<Integer>[]map;
int v, e;
public static void main(String[] args) {
new HasCycle().run();
}
public void run() {
Scanner in = new Scanner(System.in);
v = in.nextInt();
e = in.nextInt();
map = new LinkedList[v];
visit = new boolean[v];
for(int i = 0; i < v; i++) {
map[i] = new LinkedList<>();
}
for(int i = 0; i < e; i++ ) {
int a = in.nextInt();
int b = in.nextInt();
map[a].offer(b);
map[b].offer(a);
}
dfs(0, 0);
System.out.println(isHasCycle);
}
public void dfs(int cur, int parent) {
visit[cur] = true;
for(int i = 0; i < map[cur].size(); i++ ) {
int w = map[cur].get(i);
if(!visit[w]) {
dfs(w, cur);
}
else if(w != parent) {
isHasCycle = true;
return;
}
}
}
}