import java.util.*;
public class Solution {
public boolean canFinish (int numProject, ArrayList<ArrayList<Integer>> groups) {
Map<Integer,GNode> graph = new HashMap<>();
for (int i = 0; i <numProject ; i++) {
graph.put(i,new GNode(i));
}
for (ArrayList<Integer> group : groups) {
int vf = group.get(1);
int tf = group.get(0);
GNode fn = graph.get(vf);
GNode tn = graph.get(tf);
fn.nexts.add(tn);
tn.in++;
}
Queue<GNode> q0 = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
for(int k: graph.keySet()){
if(graph.get(k).in==0){
q0.add(graph.get(k));
visited.add(graph.get(k).data);
}
}
List<Integer> ll = new ArrayList<>();
while (!q0.isEmpty()){
int size = q0.size();
for (int i = 0; i <size ; i++) {
GNode pop = q0.poll();
ll.add(pop.data);
for (GNode next : pop.nexts) {
if(--next.in==0){
if(visited.contains(next.data)) return false;
q0.add(next);
visited.add(next.data);
}
}
}
}
return ll.size() == numProject? true: false;
}
static class GNode{
int data;
int in;
List<GNode> nexts;
public GNode(int d){
data =d;
in =0;
nexts = new ArrayList<>();
}
}
}