DFS解207. Course Schedule(判断有向图是否存在环)

题目

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.

For another example

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门课程,并且给了这些课程修的次序,判断这些课程能否合理地修完。比如2门课程,[1,0]这一对说明要修1课程必须要修0课程,这样的话2门课程就可以先修0课程,再修1课程,能够合理修完。如果2门课程,[1,0],[0,1]说明修1课程必须要修0课程,修0课程必须要修1课程,那么无论怎么修,都不能满足条件,因此这2门课程不能合理修完

思路分析

这就是很简单的图论判断有向图是否有环的问题。我们可以对其中的节点分3种状态。0表示这个节点没有被遍历,-1表示这个节点正在被遍历,1表示这个节点已经被遍历完毕,如果有2个节点之间有边,并且两个节点的状态相等,那么就说明在这个有向图中存在环

AC代码

#include <iostream>
#include <memory.h>
#include <vector>
#include <set>
using namespace std;
int a[2000][2000], visit[2000];
bool is_ascylic;
class Solution {
public:
    void dfs(int sp, int ep) {
        visit[sp] = -1;
        for (int i = 0; i < ep; ++i) {
            if (a[sp][i] == 1 && visit[i] == 0) {
                dfs(i, ep);
                visit[i] = 1;
            }
            if (a[sp][i] == 1 && visit[i] == -1) {
                is_ascylic = true;
                return;
            }
        }
    }
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        is_ascylic = false;
        set<int> appear_num;
        memset(a, 0, sizeof(a));
        memset(visit, 0, sizeof(visit));
        int len = prerequisites.size();
        for (int i = 0; i < len; ++i) {
            a[prerequisites[i].first][prerequisites[i].second] = 1;
            appear_num.insert(prerequisites[i].first);
        }
        for (int i = 0; i < numCourses; ++i) {
            if (!visit[i]) {
                dfs(i, numCourses);
                visit[i] = 1;
            }
        }
        return !is_ascylic;
    }
};
int main() {
    Solution s;
    pair<int, int> pp(1, 0);
    pair<int, int> ppp(0, 1);
    vector<pair<int, int>> vpp;
    vpp.push_back(pp);
    vpp.push_back(ppp);
    std::cout << s.canFinish(3, vpp) << std::endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值