算法练习5:leetcode习题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?

Note:

1.The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
2.You may assume that there are no duplicate edges in the input prerequisites.

Example 1:
Input: 2, [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: 2, [[1,0],[0,1]]
Output: false
Explanation: 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.

算法思路

这道题等价于判断一个有向图是否有环,我们回顾遍历图的方法,深度优先(DFS)和宽度优先(BFS)都是可取的。下面给出宽度优先思想的代码。
主要步骤:

  1. 建立一个前置课程的邻接链表,标记所有课程未完成
  2. 找到一个未完成前置课程数为0的课程,标记为可完成,并从其他课程的链表中删除这个课程
  3. 重复第二步,如果能依次找到Numcourse个完成的课程则返回成功,否则失败。

C++代码

class Solution {
public:
    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
        vector<list<int>> pre(numCourses);
        for (int i = 0; i < prerequisites.size(); ++i)
        {
            pre[prerequisites[i].first].push_back(prerequisites[i].second);
        }

        bool flag[numCourses] = {false};
     
        for (int i = 0; i < numCourses; ++i)
        {
            int j;
            for (j = 0; j < numCourses; ++j){
                if (!flag[j] && pre[j].size() == 0) {
                    break;
                }
            }
            if (j == numCourses) return false;
            for (int k = 0; k < numCourses; ++k)
            {
                pre[k].remove(j);
            }
            flag[j] = true;           
        } 
        return true;         
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37779608/article/details/82934885