207. Course Schedule

207. Course Schedule

  • Total Accepted: 73976 
  • Total Submissions: 238137
  • Difficulty: Medium 
  • Contributors: Admin

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?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

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:

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



题目:

有numCourse个课程,其中有些课程有前导条件,给出这些前导条件,判断是否能够完成所有的课程。


解题思路:

这是一道典型的拓扑排序题,每个前导条件是图的一条边。拓扑排序的基本思路是循环执行以下两步,直至不存在入度为零的点:(1)选择一个入度为零的点并输出这个点;(2)从图中删除这个点以及它的所有出边。循环结束后若输出的顶点数小于图中所有顶点数,则说明图中有回路,不能完成这些课程;若输出的顶点数等于图中所有顶点数,则输出的序列就是一种拓扑排序,课程可以按照这个顺序完成。

题中输入的前导条件是图中的一条边,这样的结构并不方便进行操作,所以首先需要创建一个图。我选择使用邻接表来表示这个图。另外使用一个数组来储存每个点的入度。每当输出一个点就将其指向的所有顶点的入度减一,用count来记录访问过的点,一直按照前面所说的循环直至没有入度为零的顶点,再将 count与numCourses比较。


代码:

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>> graph(numCourses);
		vector<int> indegree(numCourses, 0);
		for(int i = 0; i < prerequisites.size(); i++){
			graph[prerequisites[i].second].push_back(prerequisites[i].first);
			indegree[prerequisites[i].first]++;
		}
		queue<int> course_finished;
		for(int i = 0; i < numCourses; i++){
			if(indegree[i] == 0)
				course_finished.push(i);
		}
		int count = 0;
		while(!course_finished.empty()){
			int cur = course_finished.front();
			course_finished.pop();
			count++;
			for(int i = 0; i < graph[cur].size(); i++){
				indegree[graph[cur][i]]--;
				if(indegree[graph[cur][i]] == 0)
					course_finished.push(graph[cur][i]);
			}
		}
		return count == numCourses;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值