-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBipartiteGraphDfsBased.cs
More file actions
47 lines (37 loc) · 1.25 KB
/
Copy pathBipartiteGraphDfsBased.cs
File metadata and controls
47 lines (37 loc) · 1.25 KB
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
using System.Collections.Generic;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
public class BipartiteGraphDfsBased
{
#pragma warning disable CA1822 // Mark members as static
public bool IsBipartite(int[][] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return default;
var colors = new int[graph.Length];
for (var i = 0; i < colors.Length; i++) colors[i] = -1;
for (var i = 0; i < colors.Length; i++)
if (colors[i] == -1)
if (!Dfs(graph, i, 1, colors))
return false;
return true;
}
private static bool Dfs(IReadOnlyList<int[]> graph, int currentVertex, int color, IList<int> colors)
{
var flipColor = 1 ^ colors[currentVertex];
colors[currentVertex] = color;
for (var i = 0; i < graph.Count; i++)
{
if (graph[currentVertex][i] < 1) continue;
if (colors[i] != -1)
{
if (colors[i] == colors[currentVertex]) return false;
}
else
{
var result = Dfs(graph, i, flipColor, colors);
if (!result) return false;
}
}
return true;
}
}