LeetCode解题分享:207. Course Schedule

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/DaVinciL/article/details/99694007
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;
	}
};

展开阅读全文

没有更多推荐了,返回首页