Leetcode 207. Course Schedule

来源:互联网 发布:开淘宝网店难吗 编辑:程序博客网 时间:2024/05/29 04:45
/** * Build the graph using the list of edges. * The idea is to check is the graph has circle. * Start from nodes which indegree are zero and traverse the whole graph using BFS. * A variable count to the indicate the total number of courses we can take. * If count == numCourses return true. * Therefore, if the graph has circle, the count must less than total nodes in the graph */ public class Solution {    public boolean canFinish(int numCourses, int[][] prerequisites) {        // build the graph        HashMap<Integer, HashSet<Integer>> graph = buildGraph(prerequisites);                // calculate indegrees for all nodes in the graph        HashMap<Integer, Integer> map = new HashMap<>();        for (Integer node : graph.keySet()) {            // check the neighbors for a node            for (Integer neighbor : graph.get(node)) {                if (map.containsKey(neighbor)) {                    map.put(neighbor, map.get(neighbor)+1);                } else {                    map.put(neighbor, 1);                }            }        }                // find all nodes with zero indegree and save them in a queue        // then do the BFS on the graph        Queue<Integer> queue = new LinkedList<>();        HashSet<Integer> set = new HashSet<>();        for (int i=0; i<numCourses; i++) {            if (!map.containsKey(i)) {                queue.offer(i);                set.add(i);            }        }                int count = 0;        while (!queue.isEmpty()) {            count++;            Integer node = queue.poll();            HashSet<Integer> neighbors = graph.get(node);            if (neighbors != null) {                for (Integer neighbor : neighbors) {                    // decrease the indegree by 1                    map.put(neighbor, map.get(neighbor)-1);                    if (map.get(neighbor) == 0) {                        queue.offer(neighbor);                        set.add(neighbor);                    }                }            }        }                // if graph has circle, count must less than # of nodes         return (count == numCourses);    }        private HashMap<Integer, HashSet<Integer>> buildGraph(int[][] prerequisites) {        HashMap<Integer, HashSet<Integer>> graph = new HashMap<>();                for (int i=0; i<prerequisites.length; i++) {            if (graph.containsKey(prerequisites[i][1])) {                graph.get(prerequisites[i][1]).add(prerequisites[i][0]);            } else {                graph.put(prerequisites[i][1], new HashSet<>());                graph.get(prerequisites[i][1]).add(prerequisites[i][0]);            }        }                return graph;    }}

0 0
原创粉丝点击