Course Schedule

来源:互联网 发布:百度软件搜索 编辑:程序博客网 时间:2024/06/08 12:31

问题来源

问题描述

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.

问题分析

实际上仔细读完题目看完例子就明白这只是一道检查有向图中是否存在环的题目。检查有向图中的环一般而言有两种方法,DFS或者拓扑排序(可以看作BFS)。在这里我只是用了其中拓扑排序的方法来完成题目。

代码

class Solution {public:    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {        vector<vector<int>>graph(numCourses, vector<int>(numCourses, 0));        for (auto ele : prerequisites) {                graph[ele.first][ele.second] = 1;        }  // 建立邻接矩阵        stack<int> v;        vector<int> ind(numCourses);  // 记录顶点的入度        for (int i = 0; i < numCourses; i++) {            int degree = 0;            for (int j = 0; j < numCourses; j++)                if (graph[j][i] == 1) degree++;            ind[i] = degree;        }        for (int i = 0; i < numCourses; i++)            if (ind[i] == 0) v.push(i);        int vers = 0;        while(v.size()) {            int t = v.top();            v.pop();            vers++;            for (int i = 0; i < numCourses; i++)                if (graph[t][i]) {                    graph[t][i] = 0;                    ind[i]--;                    if (!ind[i])                        v.push(i);                }        }        return vers == numCourses;  // 最终能拓扑排序的顶点数目是否等于顶点数目    }};
原创粉丝点击