-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphWithAdjacencyLists.cs
61 lines (47 loc) · 1.88 KB
/
GraphWithAdjacencyLists.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
namespace rac.so.bytehaven
{
public class GraphWithAdjacencyLists
{
/* An implementation of the Graph data structure. MIT License.
Made with ♠ by Racso. https://rac.so | https://github.com/Racso */
private readonly int initialNeighborsCount;
private readonly Dictionary<int, List<int>> neighbors;
public GraphWithAdjacencyLists(int initialNodesCount, int initialNeighborsCount)
{
neighbors = new Dictionary<int, List<int>>(initialNodesCount);
this.initialNeighborsCount = initialNeighborsCount;
}
public void AddEdge(int nodeA, int nodeB)
{
if (!neighbors.ContainsKey(nodeA))
neighbors[nodeA] = new List<int>(initialNeighborsCount);
if (!neighbors.ContainsKey(nodeB))
neighbors[nodeB] = new List<int>(initialNeighborsCount);
neighbors[nodeA].Add(nodeB);
neighbors[nodeB].Add(nodeA);
}
public void RemoveEdge(int nodeA, int nodeB)
{
if (!neighbors.ContainsKey(nodeA) || !neighbors.ContainsKey(nodeB))
return;
neighbors[nodeA].Remove(nodeB);
neighbors[nodeB].Remove(nodeA);
}
public void RemoveNode(int node)
{
if (!neighbors.ContainsKey(node))
return;
foreach (int neighbor in neighbors[node])
neighbors[neighbor].Remove(node);
neighbors.Remove(node);
}
public int GetDegree(int node)
=> neighbors.ContainsKey(node) ? neighbors[node].Count : 0;
public IEnumerable<int> GetNeighbors(int node)
=> neighbors.ContainsKey(node) ? neighbors[node] : Array.Empty<int>();
public IEnumerable<int> GetNodes()
=> neighbors.Keys;
public int GetNodeCount()
=> neighbors.Count;
}
}