: Circle Detect
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
You are given a directed graph G which has N nodes and M directed edges. Your task is to detect whether it contains any circle.
输入
The first line contains an integer T denoting the number of test cases. (1 <= T <= 5)
For each test case the first line contains two integers N and M. (1 <= N, M <= 100000)
Then follows M lines. Each contains two integers u and v denoting there is an edge from u to v. (1 <= u, v <= N)
输出
For each test case output "YES" or "NO" denoting whether there is a circle in the graph.
样例输入
2 5 5 1 2 2 3 4 5 5 4 4 2 3 2 1 2 2 3
样例输出
YES NO
判断是否有环
用dfs或bfs
import java.util.*;
public class Main {
static ArrayList<Integer>[] g = new ArrayList[100005];
static int[] vis = new int[100005];
static boolean dfs(int u)
{
vis[u] = 1;
for(int i = 0; i < g[u].size(); i++){
int v = g[u].get(i);
if (vis[v] == 1){
return true;
}
if (vis[v] == 0){
if (dfs(v)) {
return true;
}
}
}
vis[u] = 2;
return false;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 100005; i++){
g[i] = new ArrayList();
}
int t = sc.nextInt();
for(int i = 0; i < t; i++){
int n = sc.nextInt();
for(int j = 1; j <= n; j++){
g[j].clear();
}
Arrays.fill(vis, 0);
int m = sc.nextInt();
for(int j = 0; j < m; j++){
int x = sc.nextInt();
int y = sc.nextInt();
g[x].add(y);
}
int found = 0;
for(int j = 1; j <= n; j++){
if (vis[j] == 0 && dfs(j)){
found = 1;
break;
}
}
if (found == 0){
System.out.println("NO");
} else {
System.out.println("YES");
}
}
}
}