I use DFS the same with you. Only difference is that I use hashset instead of arraylist to build the graph, but the result is time limit exceeded. Who can explain why I will get such result? Thank you!

public Map<Integer, Set<Integer>> initialGraph(int num, int[][] edges){

Map<Integer, Set<Integer>> Graph = new HashMap<>();

for (int i = 0; i < num; i++){

Graph.put(i, new HashSet<Integer>());

}

for (int i = 0; i < edges.length; i++){

Graph.get(edges[i][0]).add(edges[i][1]);

}

return Graph;

}