LeetCode解题分享:207. Course Schedule

Problem

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: true
Explanation: 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: false
Explanation: 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.
解题思路

   虽然这一题在可以采用BFS的方式求解,但是更多时候,这一题还可以采用拓扑排序的方式求解。下面是一段可用的拓扑排序的代码。

   我们首先定义了一个类来保存需要的数据,并在类中定义了需要的排序规则,然后我们对数据进行处理,利用堆排序,我们可以轻易地获取剩余元素中最小的那一个,然后将其指向的节点的入度减一,再在剩余的节点中重复操作。如果某一个最小的节点入度不为0,则表示出现了环,直接返回false。如果循环结束都没有返回,则直接返回true。

   需要注意的是,这是一个拓扑排序的模板,在执行效率上不是最高效的做法。

   代码如下:

class Course
{
public:
	int id;
	vector<int> next;
	int inDegree;

	bool operator<(const Course other) const
	{
		return this->inDegree > other.inDegree;
	}
};

class Solution {
public:
	bool canFinish(int numCourses, const vector<vector<int>>& prerequisites) {
		vector<Course> course(numCourses);
		for (int i = 0; i < numCourses; ++i)
		{
			course[i].inDegree = 0;
			course[i].id = i;
		}

		for (auto& c : prerequisites)
		{
			course[c[1]].next.push_back(c[0]);
			course[c[0]].inDegree++;
		}

		for (int i = 0; i < numCourses; ++i)
		{
			make_heap(course.begin() + i, course.end());
			if (course[i].inDegree != 0)
			{
				return false;
			}
			for (auto& id : course[i].next)
			{
				for (int j = i + 1; j < numCourses; ++j)
				{
					if (course[j].id == id)
					{
						course[j].inDegree--;
					}
				}
			}
		}
		return true;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值