关闭

LeetCode 207 Course Schedule

161人阅读 评论(0) 收藏 举报
分类:

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.

这道题其实就是检查图有没有环,检查图有没有环比较常用的方法就是使用拓扑排序,拓扑排序的思路就是不断从图中取出入度为0的点,直到不能没有入度为0的点,这样操作之后如果可以将图中所有的点全部取出,那么说明这个图是可以进行拓扑排序的,本题的具体的方法如下流程:
1. 找到入度为0的节点,入队
2. 队列是否为空
2.1 为空则跳出循环
2.2 不为空则取出一个节点,取出的记录数+1,作为当前点,遍历该当前点的所有邻接点,并将所有节点的入度均-1,表示取出了当前点,如果有节点的入度-1之后变为0,那么将其入队。
3. 取出的节点是否等于总的节点数
3.1 等于则说明没有环
3.2不等于则说明有环

具体代码如下:

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
         vector<vector<int> > relation(numCourses);
         int size = prerequisites.size();
         vector<int> indegree(numCourses);
         int outnum = 0;
         for(int i = 0; i < size; i++)
         {
             pair<int, int> pairtmp = prerequisites[i];
             relation[pairtmp.first].push_back(pairtmp.second);
             indegree[pairtmp.second]++;
         }
         stack<int> wait;
         for(int i = 0; i < numCourses; i++)
         {
             if(indegree[i] == 0)
                wait.push(i);
         }
         while(!wait.empty())
         {
             int cur = wait.top();
             wait.pop();
             outnum++;
             for(int i = 0; i < relation[cur].size(); i++)
             {
                 int adject = relation[cur][i];
                 indegree[adject]--;
                 if(indegree[adject] == 0)
                    wait.push(adject);
             }
         }
         if(outnum == numCourses)
            return true;
        else
            return false;
    }
};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14461次
    • 积分:319
    • 等级:
    • 排名:千里之外
    • 原创:19篇
    • 转载:2篇
    • 译文:0篇
    • 评论:1条
    文章分类
    最新评论