generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem33.cs
66 lines (57 loc) · 2.08 KB
/
Problem33.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/course-schedule/">Course Schedule</see>.
/// </summary>
public static class Problem33
{
/// <summary>
/// There are a total of numCourses courses you have to take, labelled from 0 to numCourses - 1.
/// You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
/// Return true if you can finish all courses. Otherwise, return false.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="numCourses">Number of courses.</param>
/// <param name="prerequisites">Array to traverse.</param>
/// <returns>True, if all courses can be finished.</returns>
public static bool CanFinish(int numCourses, int[][] prerequisites)
{
var dict = new Dictionary<int, IList<int>>();
for (var i = 0; i < prerequisites.Length; i++)
{
if (!dict.ContainsKey(prerequisites[i][0]))
{
dict.Add(prerequisites[i][0], new List<int>());
}
dict[prerequisites[i][0]].Add(prerequisites[i][1]);
}
var visited = new HashSet<int>();
var currentPath = new HashSet<int>();
for (var i = 0; i < prerequisites.Length; i++)
{
if (HasCycle(prerequisites[i][0], dict, visited, currentPath))
{
return false;
}
}
return dict.Count <= numCourses;
}
private static bool HasCycle(int course, IDictionary<int, IList<int>> dict, ISet<int> visited, ISet<int> currentPath)
{
if (!currentPath.Add(course))
{
return true;
}
if (visited.Add(course) && dict.ContainsKey(course))
{
foreach (var prerequisite in dict[course])
{
if (HasCycle(prerequisite, dict, visited, currentPath))
{
return true;
}
}
}
return !currentPath.Remove(course);
}
}