LeetCode-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?

Example 1:

Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.

题目分析:
题目说的是要我们找给定的prerequisites关系中是否存在当前所修课程与当前课程的先修课程的紊乱关系。即两门课程之间互为先修关系。

算法分析:
根据note 1我们可以知道将给定的prerequisites转成一个有向图的形式,为什么是有向图而不是无向图,因为存在课程的先修关系。由当前课程的先修课程指向当前课程,如何把二维数组转换成图的形式呢?我们可以用邻接矩阵和邻接表的形式来存课程之间的关系。

若给定的prerequisites为[[1, 0], [2, 6], [1, 7], [6, 4], [7, 0], [0, 5]]。

邻接矩阵的形式为:

在这里插入图片描述

邻接表的形式为:
在这里插入图片描述
可见用邻接矩阵的存储太浪费空间,所以选择用邻接表储存。

那么怎么用储存呢?可以使用map<int, vector<int>>来存储,把当前课程作为first,先修课程作为second,则对于prerequisites的每一对关系,可以用map[edges[1]].push_back(edges[0]);来将二维数组转换成邻接表。

那么怎么判断存在紊乱呢。我们使用dfs遍历每一个当前课程的邻居结点,若在遍历的过程中存在正在访问的结点,即形成了一个环,则返回true,若每一个结点都遍历完毕后不存在环,则返回false,若在遍历的过程中当前结点即未被访问过也没有正在访问,则标记为正在访问,并由此点出发遍历其邻居结点,若其邻居结点不存在正在访问的结点,则将此点标记为访问过,若存在,则形成环,返回true。

算法设计:拓扑排序,dfs,图论

代码:

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        vector<int> visited(numCourses, 0);
        
        //use example[[1, 0], [2, 6], [1, 7], [6, 4], [7, 0], [0, 5]]
        //Convert a two-dimensional array into a graph using an adjacency list
        unordered_map<int, vector<int>> map;
        for(auto& edges : prerequisites){
            map[edges[1]].push_back(edges[0]);
        }
        
        for(auto &node : map){
            //if dfs return true means have cycle
            if(dfs(node.first, visited, map)) return false;
        }
        return true;
    }
private:
    bool dfs(int cur, vector<int>& visited, unordered_map<int, vector<int>> &map){
        //0 = unkonw, 1 = visiting, 2 = visited
        if(visited[cur] == 1) return true;
        if(visited[cur] == 2) return false;
        
        visited[cur] = 1;
        
        for(auto &neighbour : map[cur]){
            if(dfs(neighbour, visited, map)) return true;
        }
        
        visited[cur] = 2;
        
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值