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
- [leetcode] 207.Course Schedule
- Leetcode 207. Course Schedule
- 207. Course Schedule LeetCode
- leetcode 207. Course Schedule
- leetcode.207. Course Schedule
- LeetCode 207. Course Schedule
- 【LeetCode】207. Course Schedule
- [leetcode] 207. Course Schedule
- leetcode-207. Course Schedule
- leetcode 207. Course Schedule
- [LeetCode] 207. Course Schedule
- 【Leetcode】207. Course Schedule
- Leetcode 207. Course Schedule
- LeetCode 207.Course Schedule
- Leetcode 207. Course Schedule
- Leetcode 207. Course Schedule
- [LeetCode]207. Course Schedule
- Leetcode 207. Course Schedule
- Java设计模式之行为型模式(备忘录模式)
- tab选项卡的应用
- 任志强内部又放话:2017房价会比这一轮涨得更高!
- struct
- Beyond Compare 相同文件对比结果仍显示红色 解决方案
- Leetcode 207. Course Schedule
- 数据缓存机制
- IOS开发日记
- 机器学习的理解
- virtualenv安装并配置flask开发环境
- 通过JS语句判断WEB网站的访问端是电脑还是手机
- 论文笔记: Hierarchical Question-Image Co-Attention for Visual Question Answering
- Mabitis中#与$符号区别
- 中国质造代办