-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAdjacency.cs
106 lines (88 loc) · 2.8 KB
/
Adjacency.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
namespace DataStructures.AdjacencyList
{
[Serializable]
public class AdjacencyList<T>
{
private readonly Dictionary<T, HashSet<T>> dict;
public IList<T> Vertices
{
get { return dict.Keys.ToList(); }
}
public int Count
{
get { return dict.Count; }
}
public AdjacencyList()
{
dict = new Dictionary<T, HashSet<T>>();
}
public AdjacencyList(int capacity)
{
Contract.Requires<ArgumentOutOfRangeException>(capacity > 0);
dict = new Dictionary<T, HashSet<T>>(capacity);
}
public void AddVertex(T vertex)
{
Contract.Requires<ArgumentNullException>(vertex != null);
if(dict.ContainsKey(vertex))
{
return;
}
dict[vertex] = new HashSet<T>();
}
public void AddEdge(T vertex1, T vertex2)
{
Contract.Requires<ArgumentNullException>(vertex1 != null);
Contract.Requires<ArgumentNullException>(vertex2 != null);
if (!dict.ContainsKey(vertex1))
{
dict[vertex1] = new HashSet<T>();
}
if (!dict.ContainsKey(vertex2))
{
dict[vertex2] = new HashSet<T>();
}
dict[vertex1].Add(vertex2);
dict[vertex2].Add(vertex1);
}
public bool IsNeighbourOf(T vertex, T neighbour)
{
Contract.Requires<ArgumentNullException>(vertex != null);
Contract.Requires<ArgumentNullException>(neighbour != null);
return dict.ContainsKey(vertex) && dict[vertex].Contains(neighbour);
}
public IList<T> GetNeighbours(T vertex)
{
Contract.Requires<ArgumentNullException>(vertex != null);
return dict.ContainsKey(vertex)? dict[vertex].ToList(): new List<T>();
}
public IList<T> this[T vertex]
{
get
{
return GetNeighbours(vertex);
}
set
{
Contract.Requires<ArgumentNullException>(vertex != null);
dict[vertex] = new HashSet<T>(value);
}
}
public IList<Tuple<T, T>> GetEdgeList()
{
var list = new List<Tuple<T, T>>();
foreach (var entry in dict)
{
var key = entry.Key;
var hashSet = entry.Value;
list.AddRange(hashSet.Select(hashEntry => new Tuple<T, T>(key, hashEntry)));
}
return list;
}
}
}