[LeetCode] 207. Course Schedule

本文针对LeetCode上的课程安排问题进行了解析,通过将其转化为有向图,并利用拓扑排序的方法来判断是否有环,进而确定能否完成所有课程。文章详细介绍了算法实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://leetcode.com/problems/course-schedule/description/

Description

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.

解题思路

题意为给定课程数 n 和先导课程数组,数组里每一个元素为 [课程号, 先导课程号],要学习某门课程,需要先学习先导课程,问是否可以完成所有课程。

题目可以转化为有向图,每一个课程为一个顶点,有向边由 先导课程 指向 目标课程,判断该有向图是否有环,无环则可以完成所有课程,否则不能完成。

判断一个有向图是否有环有很多方法,如 DFS、BFS、拓扑排序。这里使用的是拓扑排序的方法,为方便找每个顶点可以到达的顶点,用了一个 unordered_map 将先导课程数组转化为邻接链表形式,也可以用 vector 替代。记录每一个顶点的入度,然后就跟拓扑排序一样了。最后再判断一下入度数组是否有元素不为 0,若有则有环,返回 fasle,否则返回 true

Code

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>> &prerequisites) {
        vector<int> indegree(numCourses, 0);
        unordered_map<int, list<int>> umap;
        queue<int> mq;

        for (int i = 0; i < prerequisites.size(); ++i) {
            if (umap.count(prerequisites[i].second) == 0)
                umap[prerequisites[i].second] = list<int>(1, prerequisites[i].first);
            else
                umap[prerequisites[i].second].push_back(prerequisites[i].first);
            indegree[prerequisites[i].first]++;
        }

        for (int i = 0; i < numCourses; ++i) {
            if (indegree[i] == 0) mq.push(i);
        }

        while (!mq.empty()) {
            int start = mq.front();
            mq.pop();

            for (auto it = umap[start].begin(); it != umap[start].end(); ++it) {
                indegree[*it]--;
                if (indegree[*it] == 0) mq.push(*it);
            }
        }

        for (auto x: indegree) if (x != 0) return false;
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值