Leetcode 207/210. Course Schedule I/II

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, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

在这里插入图片描述

method 1 topological sort

有严格的顺序要求,所以自然而然想到拓扑排序
输入的是边集,所以要建图才好使用拓扑排序,这里选择邻接表作为图的数据结构(声明一个vector的二维数组vector<vector> edge(numCourses);)
使用队列进行BFS搜索,进行拓扑排序

vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites) {
    vector<vector<int>> edge(numCourses);

	int* indegree = new int[numCourses];
	for (int i = 0; i < numCourses; i++)
		indegree[i] = 0;

	for (int i = 0; i < prerequisites.size(); i++)
	{
		indegree[prerequisites[i][0]]++;
		edge[prerequisites[i][1]].push_back(prerequisites[i][0]);
	}

	queue<int> q; //保存入度为0的结点
	for (int i = 0; i < numCourses; i++)
	{
		if (indegree[i] == 0)
			q.push(i);
	}

	vector<int> ans;
	while (!q.empty())
	{
		int v = q.front(); q.pop();
		ans.push_back(v);
		for (int i = 0; i < edge[v].size(); i++)
		{
			if (--indegree[edge[v][i]] == 0)
				q.push(edge[v][i]);
		}
	}

    if(ans.size() < numCourses) ans.clear();
	return ans;
    }

如果ans的大小小于节点个数,说明存在环

summary

  1. 有严格的顺序要求,使用BFS建立拓扑排序
  2. 本题拓扑排序是模板代码,需要牢记
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值