-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcourse-schedule.linq
More file actions
57 lines (50 loc) · 941 Bytes
/
course-schedule.linq
File metadata and controls
57 lines (50 loc) · 941 Bytes
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
<Query Kind="Program" />
//https://leetcode.com/problems/course-schedule/
void Main()
{
var pr = new int[][]{ new []{0, 1},
new []{1, 0}};
CanFinish(2, pr).Dump();
}
bool CanFinish(int numCourses, int[][] prerequisites)
{
//buld graph
var g = new Dictionary<int, List<int>>();
foreach (var pair in prerequisites)
{
if (g.Keys.Contains(pair[0]))
{
g[pair[0]].Add(pair[1]);
}
else
{
g[pair[0]] = new List<int> { pair[1] };
}
}
g.Dump();
HashSet<int> visited = new HashSet<int>();
bool result = true;
//run DFS
foreach (var v in g.Keys)
{
result &= Explore(g, v, v, visited);
}
return result;
}
bool Explore(Dictionary<int, List<int>> g, int v, int start, HashSet<int> visited)
{
bool result = true;
foreach (var u in g[v])
{
if (u == start)
{
return false;
}
if (visited.Contains(u) == false)
{
visited.Add(u);
result &= Explore(g, u, start, visited);
}
}
return result;
}