LeetCode题解(Week5):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.

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.

中文大意

给定一个图的所有边,每一条边代表一门课与它所依赖的课程,比如[0,1]代表课程0需要先上完课程1再上,问按照这个图,有没有可能得到一种合理的安排:能不能先上完所有依赖的课再上该课?

实际上这是一道关于拓扑排序的经典例题

题解

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) 
    {
       vector<int> in_order(numCourses,0);
       bool res = true;
       int v_del = 0;
       //求出每一个节点的入度
       for(int i = 0 ; i < prerequisites.size(); i ++)
       {
           in_order[prerequisites[i].second] ++;
       }

       while(v_del<numCourses)
       {
           //找到入度为0的节点
           int ind0 = -1;
           for(int i = 0 ; i < in_order.size();i ++)
           {
               if(in_order[i]==0)
                    ind0 = i;
           }

           //如果入度为0的点不存在,则说明不可能
           if(ind0 == -1) break;

           //删除这个节点以及改变对应的入度
           in_order[ind0] = -1;
           v_del ++;
           for(int i = 0 ;i < prerequisites.size();i++)
           {
               if(ind0==prerequisites[i].first)
                    in_order[prerequisites[i].second]--;
           }
       }
       return v_del==numCourses;
    }
};

解析

其实这道题是一个拓扑排序的模型。对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边(u,v)∈E(G),则u在线性序列中出现在v之前。现在题目要做不要求给出排序结果,只要求判断图中有没有环即可,问题就变成了,在图中进行拓扑排序能否成功。

拓扑排序中,每次先找到入度为0的点,然后把对应的边都去掉。但是在这里,由于题目的关系,我没有这样做,直接将入度为0的点找到以后,把入度置为-1,然后以它为起点的边,终点对应节点的入度减1,最终如果删掉的节点等于总节点数,就说明成功。

这样做的算法复杂度为O(V*E),V为节点个数,E为边数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值