leetcode-Course Schedule

题目:leetcode

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.


分析:

本题目可转化为 “判断有向图中是否有环”。

1、把数组prerequisites中的内容放进哈希表table,table的key是课程编号,value是一个数组,记录了key代表的课程的约束条件(即上完value中的课程,才能上key的课程)。如果每一门课程当成平面上的一个点,那么key和value中的每一门课程,可以分别连成一条有向路径。

2、利用回溯法,如果没有环,则把相应的“路径”删除,直到把有向图删光。若有环,则整个程序返回false。


class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
        if(prerequisites.size()<=1)
            return true;
        
        unordered_map<int,vector<int>> table;
        for(auto &i:prerequisites)
        {
            table[i[0]].push_back(i[1]);
        }
       vector<int> path;
        while(!table.empty())
        {
            auto it=table.begin();
            path.push_back(it->first);
            if(HasLoop(table,it->first,path))
                return false;
            path.pop_back();
        }
        return true;
    }
    //判断是否有环,有环<span style="font-family: Arial, Helvetica, sans-serif;">的话返回真,否则返回假</span>
    bool HasLoop( unordered_map<int,vector<int>> &table,const int &begin,vector<int> &path)
    {
       if(table.count(begin)==0)
         return false;
       while(!table[begin].empty())
       {
           int temp=table[begin].back();
           if(find(path.begin(),path.end(),temp)!=path.end())
                return true;
            path.push_back(temp);
           if(HasLoop(table,temp,path))
                return true;
            path.pop_back();
            table[begin].pop_back();
       }
       table.erase(begin);
       return false;
    }
    
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值