All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0201_0300.s0210_course_schedule_ii.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show newest version
package g0201_0300.s0210_course_schedule_ii;

// #Medium #Top_Interview_Questions #Depth_First_Search #Breadth_First_Search #Graph
// #Topological_Sort

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        Map> graph = new HashMap<>();
        for (int i = 0; i < numCourses; i++) {
            graph.put(i, new ArrayList<>());
        }

        for (int[] classes : prerequisites) {
            graph.get(classes[0]).add(classes[1]);
        }

        List output = new ArrayList<>();
        Map visited = new HashMap<>();
        for (int c : graph.keySet()) {
            if (dfs(c, graph, visited, output)) {
                return new int[0];
            }
        }

        int[] res = new int[output.size()];
        for (int i = 0; i < output.size(); i++) {
            res[i] = output.get(i);
        }
        return res;
    }

    private boolean dfs(
            int course,
            Map> graph,
            Map visited,
            List output) {
        if (visited.containsKey(course)) {
            return visited.get(course);
        }

        visited.put(course, true);

        for (int c : graph.get(course)) {
            if (dfs(c, graph, visited, output)) {
                return true;
            }
        }

        visited.put(course, false);
        output.add(course);
        return false;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy