private boolean canFinish(HashMap<Integer, List<Integer>> graph, int[] visited, int n, List<Integer> res) {
        if (visited[n] == -1) return false;
        if (visited[n] == 1) return true;
        visited[n] = -1;
        if (graph.containsKey(n)) {
            for (int next : graph.get(n)) {
                if (!canFinish(graph, visited, next, res)) return false;
            }
        }
        visited[n] = 1;
        res.add(0, n); // add to head
        return true;
    }