Course Schedule

本文探讨了一个经典的图论问题——如何判断能否完成所有课程的问题。通过分析课程先修条件构成的有向图,采用拓扑排序的方法来判断图中是否存在环,从而确定能否完成所有课程。

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

问题来源

问题描述

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:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

问题分析

实际上仔细读完题目看完例子就明白这只是一道检查有向图中是否存在环的题目。检查有向图中的环一般而言有两种方法,DFS或者拓扑排序(可以看作BFS)。在这里我只是用了其中拓扑排序的方法来完成题目。

代码

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<vector<int>>graph(numCourses, vector<int>(numCourses, 0));
        for (auto ele : prerequisites) {
                graph[ele.first][ele.second] = 1;
        }  // 建立邻接矩阵

        stack<int> v;
        vector<int> ind(numCourses);  // 记录顶点的入度
        for (int i = 0; i < numCourses; i++) {
            int degree = 0;
            for (int j = 0; j < numCourses; j++)
                if (graph[j][i] == 1) degree++;
            ind[i] = degree;
        }
        for (int i = 0; i < numCourses; i++)
            if (ind[i] == 0) v.push(i);

        int vers = 0;
        while(v.size()) {
            int t = v.top();
            v.pop();
            vers++;
            for (int i = 0; i < numCourses; i++)
                if (graph[t][i]) {
                    graph[t][i] = 0;
                    ind[i]--;
                    if (!ind[i])
                        v.push(i);
                }

        }
        return vers == numCourses;  // 最终能拓扑排序的顶点数目是否等于顶点数目
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值