博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
207. Course Schedule
阅读量:2351 次
发布时间:2019-05-10

本文共 2498 字,大约阅读时间需要 8 分钟。

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 1:

Input: 2, [[1,0]] Output: trueExplanation: There are a total of 2 courses to take.              To take course 1 you should have finished course 0. So it is possible.

Example 2:

Input: 2, [[1,0],[0,1]]Output: falseExplanation: There are a total of 2 courses to take.              To take course 1 you should have finished course 0, and to take course 0 you should             also have finished course 1. So it is impossible.

Note:

The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

我的想法

拓扑排序无疑了。这里有一点需要注意的是,map的key应该是被依赖的点,而value是依赖于key的点。indegree中value是key的入度。需要注意剔除重复的依赖关系

public class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
Queue
queue = new LinkedList<>(); HashMap
> map = new HashMap<>(); HashMap
indegree = new HashMap<>(); int counter = 0; //initialize indegree and map for(int i = 0; i < numCourses; i++) {
map.put(i, new HashSet
()); indegree.put(i, 0); } //calculate the indegree of each courses for(int[] seq : prerequisites) {
//avoid repeated prerequisites if(map.get(seq[1]).add(seq[0])) {
indegree.put(seq[0], indegree.get(seq[0]) + 1); } } //put zero indegree points into the queue for(int i = 0; i < numCourses; i++) {
if(indegree.get(i) == 0) {
queue.offer(i); } } //doing the topological sorting while(!queue.isEmpty()){
int preCourse = queue.poll(); counter++; for(Integer nextCourse : map.get(preCourse)) {
indegree.put(nextCourse, indegree.get(nextCourse) - 1); if(indegree.get(nextCourse) == 0) {
queue.offer(nextCourse); } } } return numCourses == counter; }}

解答

转载地址:http://okqvb.baihongyu.com/

你可能感兴趣的文章
SpringCloud 2.x学习笔记:4、Zuul(Greenwich版本)
查看>>
ajax提交JSON数组及Springboot接收转换为list类
查看>>
SpringCloud 2.x学习笔记:5、Config(Greenwich版本)
查看>>
RabbitMQ安装、配置与入门
查看>>
Java异常
查看>>
Ibatis代码自动生成工具
查看>>
ant build.xml教程详解
查看>>
彻底理解ThreadLocal
查看>>
localhost与127.0.0.1的区别
查看>>
windows下的host文件在哪里,有什么作用?
查看>>
操作系统之字符集
查看>>
OSI和TCP/IP
查看>>
Redis集群搭建最佳实践
查看>>
ZooKeeper原理及使用
查看>>
Zookeeper集群搭建
查看>>
利用TypePerf.exe查看性能
查看>>
分布式框架Dubbo
查看>>
解决PKIX:unable to find valid certification path to requested target 的问题
查看>>
hibernate.cfg.xml配置详解
查看>>
hibernate+proxool的数据库连接池配置方法
查看>>