-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBiconnectedGraph.cs
More file actions
69 lines (56 loc) · 2.54 KB
/
BiconnectedGraph.cs
File metadata and controls
69 lines (56 loc) · 2.54 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using AlgorithmsAndDataStructures.Algorithms.Graph.Common;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
public class BiConnectedGraph
{
private const int NullParent = -1;
#pragma warning disable CA1822 // Mark members as static
public bool IsBiConnected(UndirectedGraph graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return default;
var vertices = graph.Vertices();
var visited = new bool[vertices.Length];
var parents = new int[vertices.Length];
var discoveryTimes = new int[vertices.Length];
var lowestReachableDiscoveryTime = new int[vertices.Length];
parents[0] = NullParent;
var result = IsBiConnected(vertices, 0, 0, visited, parents, discoveryTimes, lowestReachableDiscoveryTime) &&
visited.All(arg => arg);
return result;
}
private static bool IsBiConnected(
IReadOnlyList<List<int>> vertices,
int currentVertex,
int currentDiscoveryTime,
IList<bool> visited, IList<int> parents,
IList<int> discoveryTimes,
IList<int> lowestReachableDiscoveryTime)
{
visited[currentVertex] = true;
discoveryTimes[currentVertex] = lowestReachableDiscoveryTime[currentVertex] = currentDiscoveryTime++;
var children = 0;
foreach (var adjacentVertex in vertices[currentVertex])
if (!visited[adjacentVertex])
{
children++;
parents[adjacentVertex] = currentVertex;
var result = IsBiConnected(vertices, adjacentVertex, currentDiscoveryTime, visited, parents,
discoveryTimes, lowestReachableDiscoveryTime);
if (!result) return false;
lowestReachableDiscoveryTime[currentVertex] = Math.Min(lowestReachableDiscoveryTime[currentVertex],
lowestReachableDiscoveryTime[adjacentVertex]);
if (parents[currentVertex] == NullParent && children > 1) return false;
if (parents[currentVertex] != NullParent &&
lowestReachableDiscoveryTime[adjacentVertex] >= discoveryTimes[currentVertex]) return false;
}
else if (adjacentVertex != parents[currentVertex])
{
lowestReachableDiscoveryTime[currentVertex] = Math.Min(lowestReachableDiscoveryTime[currentVertex],
discoveryTimes[adjacentVertex]);
}
return true;
}
}