第四周:[Leetcode]207. Course Schedule

来源:互联网 发布:touchslide.js 编辑:程序博客网 时间:2024/06/02 06:51

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.


课程节点之间可以组成一个有向图,所求即该图是否可形成一个拓扑序列。将课程节点信息用邻接表的形式储存,使用队列实现拓扑序列的寻找。


class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {    vector<vector<int>> m(numCourses,vector<int>());    vector<bool> v(numCourses,false);    vector<int> p(numCourses,0);    queue<int> q;    int i,node;    for(i = 0; i< prerequisites.size();i++){      m[prerequisites[i].second].push_back(prerequisites[i].first);        p[prerequisites[i].first] ++;    }    for(i = 0; i < numCourses;i++)        if(p[i] == 0)            q.push(i);    while(!q.empty()){        node = q.front();        q.pop();        v[node] = 1;        vector<int>::iterator it = m[node].begin();        while(it != m[node].end()){            if((--p[*it]) == 0 && v[*it] == 0)                q.push(*it);            ++it;        }        m[node].clear();    }    for(i = 0; i < numCourses;i++)        if(v[i]==0)            return 0;    return 1;    }};
0 0
原创粉丝点击