blob: 3fa23d81abb10db69d75ed709fbad14a5d1a4f92 (
plain)
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
|
using System;
using System.Collections.Generic;
using Interfaces;
namespace Graph
{
public class Graph<T, U, V>
where T : IVertex<U, V>, new()
where U : IEdge<V>, new()
where V : IComparable<V>
{
public List<T> Vertices { get; set; } = new List<T>();
public Graph() { }
public Graph(List<T> vertices)
{
Vertices = vertices;
}
// indexer for accessing vertex with id of index
public T this[int index] { get => Vertices.Find(vertex => vertex.Id == index); }
// create virtex if needed, then add the edge to it's edges list
public void AddEdge(U edge)
{
// look for existing vertex, and use it if found
T vertex = Vertices.Find(u => u.Id == edge.U);
// if not found, create a new vertex
if (vertex == null)
{
// weird constructor call to avoid using more generics
vertex = new T();
vertex.Id = edge.U;
Vertices.Add(vertex);
}
// add the edge to the new/found vertex
vertex.Edges.Add(edge);
}
public override string ToString() => $"{String.Join("\n", Vertices)}";
}
}
|