-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBipartiteGraphBfsBased.cs
More file actions
53 lines (43 loc) · 1.44 KB
/
Copy pathBipartiteGraphBfsBased.cs
File metadata and controls
53 lines (43 loc) · 1.44 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
48
49
50
51
52
53
using System.Collections.Generic;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
public class BipartiteGraphBfsBased
{
#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 (!Bfs(graph, i, 1, colors))
return false;
return true;
}
private static bool Bfs(IReadOnlyList<int[]> graph, int currentVertex, int startColor, IList<int> colors)
{
var queue = new Queue<int>();
queue.Enqueue(currentVertex);
colors[currentVertex] = startColor;
while (queue.Count > 0)
{
var current = queue.Dequeue();
var adjacentColor = 1 ^ colors[current];
for (var i = 0; i < graph.Count; i++)
{
if (graph[current][i] < 1) continue;
if (colors[i] != -1)
{
if (colors[i] == colors[current]) return false;
}
else
{
queue.Enqueue(i);
colors[i] = adjacentColor;
}
}
}
return true;
}
}