-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution886.cs
69 lines (56 loc) · 1.54 KB
/
Solution886.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
67
68
69
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution886
{
/// <summary>
/// 886. Possible Bipartition - Medium
/// <a href="https://leetcode.com/problems/possible-bipartition">See the problem</a>
/// </summary>
public bool PossibleBipartition(int n, int[][] dislikes)
{
var graph = new Dictionary<int, List<int>>();
foreach (var dislike in dislikes)
{
if (!graph.ContainsKey(dislike[0]))
{
graph[dislike[0]] = new List<int>();
}
if (!graph.ContainsKey(dislike[1]))
{
graph[dislike[1]] = new List<int>();
}
graph[dislike[0]].Add(dislike[1]);
graph[dislike[1]].Add(dislike[0]);
}
var colors = new int[n + 1];
for (int i = 1; i <= n; i++)
{
if (colors[i] == 0 && !DFS(graph, colors, i, 1))
{
return false;
}
}
return true;
}
private bool DFS(Dictionary<int, List<int>> graph, int[] colors, int node, int color)
{
if (colors[node] != 0)
{
return colors[node] == color;
}
colors[node] = color;
if (!graph.ContainsKey(node))
{
return true;
}
foreach (var neighbor in graph[node])
{
if (!DFS(graph, colors, neighbor, -color))
{
return false;
}
}
return true;
}
}