码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】207. Course Schedule

时间:2015-06-25 11:53:30      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.

click to show more hints.

 

思路:每个连通分量,只要出现回路,即说明冲突了。

回路检测如下:

存在a->b,又存在b->c,那么增加边a->c

如果新增边c->a,发现已有a->c,在矩阵中表现为对称位置为true,则存在回路。

注:数组比vector速度快。

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        bool **preG;
        preG = new bool*[numCourses];
        for(int i = 0; i < numCourses; i ++)
            preG[i] = new bool[numCourses];
        for(int i = 0; i < numCourses; i ++)
        {
            for(int j = 0; j < numCourses; j ++)
                preG[i][j] = false;
        }
        for(int i = 0; i < prerequisites.size(); i ++)
        {
            int a = prerequisites[i].first;
            int b = prerequisites[i].second;
            if(preG[b][a] == true)
                return false;
            else
            {
                preG[a][b] = true;
                for(int j = 0; j < numCourses; j ++)
                {
                    if(preG[j][a] == true)
                        preG[j][b] = true;
                }
            }
        }
        return true;
    }
};

技术分享

【LeetCode】207. Course Schedule

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4599465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!