LeetCode 207. Course Schedule

本文探讨了LeetCode第207题Course Schedule的问题解决思路,利用有向图和深度优先搜索(DFS)来判断一组课程是否存在合理的修读顺序。

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

图和dfs

LeetCode第207题CourseSchedule 难度Medium

题目描述:
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.

这题的相当于给定一个有向图,课程是有向图的顶点,课程之间的依赖关系相当于有向图的边。修完所有课程的顺序相当于对图进行一次拓扑排序。而问题问的是能否修完课程,即能否进行拓扑排序。若不能进行拓扑排序,说明有向图中有环,也就是存在回边(back edge)。

因此先由输入数据构建起有向图(邻接表形式),找出图中所有的源。
1. 若没有源,则图中只有环,返回false。
2. 若存在源,分别从每个源开始进行dfs。在dfs的过程中,访问顶点n时将pre[n]标志为true,离开时将post[n]标志为true。倘若将要访问的下一个顶点m的pre[m]为true而post[m]为false,则说明在dfs过程构建的树中,n是m的子树中的节点,故n->m的边是回边,以此可以判断图中有环,返回false。从所有源开始遍历完后,要检查是否顶点全部被遍历过,以排除有些环无源未被遍历的情况。

具体代码如下:

struct Node {
    int value;
    Node* next;
    Node(int v): value(v), next(NULL) {}
};

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        constructGraph(numCourses, prerequisites);

        int s, i;

        for (i = 0; i < numCourses; i++) {
            pre.push_back(false);
            post.push_back(false);
        }

        // dfs每个源
        for (s = 0; s < numCourses; s++) {
            if (source[s]) {
                if (dfs(s) == false)
                    return false;
            }
        }

        // 判断是否所有顶点都被访问过
        for (i = 0; i < numCourses; i++) {
            if (pre[i] == false) break;
        }

        destructGraph(numCourses);
        if (i == numCourses) return true;
        else return false;
    }


private:
    bool constructGraph(int numCourses, vector<pair<int, int>>& prerequisites) {
        for (int i = 0; i < numCourses; i++) {
            adjList.push_back(NULL);
            source.push_back(true);
        }
        for (int i = 0; i < prerequisites.size(); i++) {
            Node* p = adjList[prerequisites[i].first];
            // 有入边的顶点不是源
            source[prerequisites[i].second] = false;
            if (p == NULL) {
                adjList[prerequisites[i].first] = new Node(prerequisites[i].second);
            } else {
                while (p->next != NULL) {
                    p = p->next;
                }
                p->next = new Node(prerequisites[i].second);
            }
        }
        return true;
    }

    bool destructGraph(int numCourses) {
        for (int i = 0; i < numCourses; i++) {
            if (adjList[i] != NULL) {
                Node* del = adjList[i];
                Node* p = del->next;
                while (p != NULL) {
                    delete del;
                    del = p;
                    p = del->next;
                }
                delete del;
            }
        }
        return true;
    }

    bool dfs(int n) {
        pre[n] = true;
        Node* p = adjList[n];
            // 判断这条边是否是回边
            if (pre[p->value] == true && post[p->value] == false)
                return false;
            if (pre[p->value] == false) {
                if (dfs(p->value) == false) return false;
            }
            p = p->next;
        }
        post[n] = true;
        return true;
    }

private:
    //邻接表
    vector<Node*> adjList;

    //储存pre和post标志
    vector<bool> pre;
    vector<bool> post;

    //储存源
    vector<bool> source;
};

结果:
37 / 37 test cases passed.
Status: Accepted
Runtime: 12 ms
Your runtime beats 86.48 % of cpp submissions.

是图和dfs很基础的应用的题目~

### LeetCode Hot 100 Problems 列表 LeetCode 的热门题目列表通常由社区投票选出,涵盖了各种难度级别的经典编程挑战。这些题目对于准备技术面试非常有帮助。以下是部分 LeetCode 热门 100 题目列表: #### 数组与字符串 1. **两数之和 (Two Sum)** 2. **三数之和 (3Sum)** 3. **无重复字符的最长子串 (Longest Substring Without Repeating Characters)** 4. **寻找两个正序数组的中位数 (Median of Two Sorted Arrays)** #### 动态规划 5. **爬楼梯 (Climbing Stairs)** 6. **不同的二叉搜索树 (Unique Binary Search Trees)** 7. **最大子序列和 (Maximum Subarray)** #### 字符串处理 8. **有效的括号 (Valid Parentheses)** 9. **最小覆盖子串 (Minimum Window Substring)** 10. **字母异位词分组 (Group Anagrams)** #### 图论 11. **岛屿数量 (Number of Islands)** 12. **课程表 II (Course Schedule II)** #### 排序与查找 13. **最接近原点的 K 个点 (K Closest Points to Origin)** 14. **接雨水 (Trapping Rain Water)** 15. **最长连续序列 (Longest Consecutive Sequence)[^2]** #### 堆栈与队列 16. **每日温度 (Daily Temperatures)** 17. **滑动窗口最大值 (Sliding Window Maximum)** #### 树结构 18. **验证二叉搜索树 (Validate Binary Search Tree)** 19. **二叉树的最大路径和 (Binary Tree Maximum Path Sum)** 20. **从前序与中序遍历序列构造二叉树 (Construct Binary Tree from Preorder and Inorder Traversal)** #### 并查集 21. **冗余连接 II (Redundant Connection II)** #### 贪心算法 22. **跳跃游戏 (Jump Game)** 23. **分割等和子集 (Partition Equal Subset Sum)** #### 双指针技巧 24. **环形链表 II (Linked List Cycle II)[^1]** 25. **相交链表 (Intersection of Two Linked Lists)** #### 其他重要题目 26. **LRU缓存机制 (LRU Cache)** 27. **打家劫舍系列 (House Robber I & II)** 28. **编辑距离 (Edit Distance)** 29. **单词拆分 (Word Break)** 此列表并非官方发布版本而是基于社区反馈整理而成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值