2023-09-09 LeetCode每日一题(课程表)

2023-09-09每日一题

一、题目编号

复制代码
207. 课程表

二、题目链接

点击跳转到题目位置

三、题目描述

你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。

在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisitesi = ai, bi ,表示如果要学习课程 ai 则 必须 先学习课程 bi 。

  • 例如,先修课程对 0, 1 表示:想要学习课程 0 ,你需要先完成课程 1 。
    请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。

示例 1:

示例 2:

提示:

  • 1 <= numCourses <= 2000
  • 0 <= prerequisites.length <= 5000
  • prerequisitesi.length == 2
  • 0 <= ai, bi < numCourses
  • prerequisitesi 中的所有课程对 互不相同

四、解题代码

cpp 复制代码
class Solution {
    #define maxn 100010
    vector<int> edges[maxn];
    int deg[maxn];

    void addEdge(int v, int u){
        edges[u].push_back(v);
        ++deg[v];
    }

public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        int i;
        int n=prerequisites.size();
        queue<int> q;
        int hash[maxn];
        memset(hash,0,sizeof(hash));
        for(i=0;i<numCourses;i++){
            edges[i].clear();
            deg[i] = 0;
            hash[i] = 0;
        }
       
        for(int i=0;i<n;i++){
            addEdge(prerequisites[i][1],prerequisites[i][0]);
        }
        int x=numCourses;
        for(int i=0;i<numCourses;i++){
            if(!deg[i]){
                q.push(i);
                x--;
                hash[i]=1;
            }
        }

        while( !q.empty() ){
            int u=q.front();
            q.pop();
            for(int i=0;i<edges[u].size();i++){
                int v=edges[u][i];
                deg[v]--;
                if(hash[v]==0 && deg[v]==0){
                    q.push(v);
                    hash[v]=1;
                    x--;
                }
            }      
        }
        if(x==0){
            return true;
        }
    return false;
    }
};

五、解题思路

(1) 使用拓扑排序可以很轻松的的解决这道题目。这也是拓扑排序的一道经典例题。

相关推荐
ysu_03147 小时前
05 | 持久化撤销提示非核心功能
算法·游戏程序
浮沉9878 小时前
二分查找算法概述&通用模板
算法
Keven_119 小时前
算法札记:SPFA判负环算法的证明
算法
什巳9 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
Jerry9 小时前
LeetCode 347. 前 K 个高频元素
算法
Young Doro10 小时前
SAC 算法
线性代数·算法·机器学习
罗超驿10 小时前
2.算法效率的核心密码:时间复杂度和空间复杂度详解
java·数据结构·算法
:-)10 小时前
算法-堆排序
数据结构·算法·排序算法