summaryrefslogtreecommitdiffstats
path: root/Graph.cs
blob: 10381f18fc719df91c552a2a2eda86e1d0845c28 (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
using System;
using System.Collections.Generic;

namespace Graph
{
    public class Graph<T> where T : IComparable<T>
    {
        public List<Vertex<T>> Vertices { get; set; } = new List<Vertex<T>>();

        public Graph() { }

        public Graph(List<Vertex<T>> vertices)
        {
            Vertices = vertices;
        }

        // indexer for accessing vertex with id of index 
        public Vertex<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(Edge<T> edge)
        {
            // look for existing vertex, and use it if found
            Vertex<T> vertex = Vertices.Find(u => u.Id == edge.U);

            if (vertex == null)
            {
                // if not found, create a new vertex
                Vertices.Add(vertex = new Vertex<T>(edge.U));
                vertex = Vertices[Vertices.Count - 1];
            }
            
            // add the edge to the new/found vertex
            vertex.Edges.Add(edge);
        }

        public override string ToString() => $"{String.Join("\n", Vertices)}";
    }

}