Leetcode 207 Solution

This article provides solution to leetcode question 207 (course-schedule)

https://leetcode.com/problems/course-schedule

Solution

class Solution {
    multimap<int, int> graph;
public:
    bool checkloop(int node, vector<int>& visited, vector<int>& summary)
    {
        if (visited[node])
            return true;

        visited[node] = 1;
        summary[node] = 1;

        for (auto it = graph.find(node); it != graph.end() && it->first == node; ++it)
        {
            if (checkloop(it->second, visited, summary))
                return true;
        }

        visited[node] = 0;

        return false;
    }

    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites)
    {
        vector<int> degree(numCourses);

        for (auto pair : prerequisites)
        {
            degree[pair.second]++;
            graph.insert(make_pair(pair.first, pair.second));
        }

        vector<int> summary(numCourses);

        for (int i = 0; i < numCourses; i++)
        {
            vector<int> visited(numCourses);

            if (degree[i] == 0)
            {
                if (checkloop(i, visited, summary))
                    return false;
            }
        }

        for (int i = 0; i < numCourses; i++)
            if (summary[i] == 0)
                return false;

        return true;
    }
};