inz-00/Assets/Map/Graph.cs
2019-08-15 20:22:18 +02:00

37 lines
962 B
C#

using System;
using System.Collections.Generic;
using System.Linq;
namespace Assets.Map
{
public class Graph<T>
{
public List<T> Vertices { get; internal set; } = new List<T>();
public ISet<(int, int)> Edges { get; internal set; } = new HashSet<(int, int)>();
public void AddEdge(int a, int b)
{
Edges.Add(a < b ? (a, b) : (b, a));
}
public IEnumerable<(int, int)> EdgesOf(int a)
{
return Edges.Where(x => x.Item1 == a || x.Item2 == a);
}
public Graph<U> Morph<U>(Func<T, U> morph)
{
var result = new Graph<U>() { Edges = Edges };
result.Vertices.AddRange(Vertices.Select(morph));
return result;
}
public IEnumerable<int> Neighbours(int vertex)
{
foreach (var (a, b) in this.EdgesOf(vertex))
yield return a == vertex ? b : a;
}
}
}