MoonTools.Graph/Graph/SimpleGraph.cs

53 lines
1.6 KiB
C#
Raw Normal View History

2019-10-24 01:05:28 +00:00
using System;
using System.Collections.Generic;
2020-02-21 02:43:25 +00:00
namespace MoonTools.Graph
2019-10-24 01:05:28 +00:00
{
abstract public class SimpleGraph<TNode, TEdgeData> : Graph<TNode, TEdgeData> where TNode : System.IEquatable<TNode>
{
protected HashSet<(TNode, TNode)> edges = new HashSet<(TNode, TNode)>();
protected Dictionary<(TNode, TNode), TEdgeData> edgeToEdgeData = new Dictionary<(TNode, TNode), TEdgeData>();
public IEnumerable<(TNode, TNode)> Edges => edges;
public int Size => edges.Count;
2019-10-24 01:47:48 +00:00
protected void BaseAddEdge(TNode v, TNode u, TEdgeData edgeData)
{
CheckNodes(v, u);
2019-10-24 04:29:26 +00:00
if (Exists(v, u)) { throw new ArgumentException($"Edge between {v} and {u} already exists in the graph"); }
2019-10-24 01:47:48 +00:00
if (v.Equals(u)) { throw new ArgumentException("Self-edges are not allowed in a simple graph. Use a multigraph instead"); }
neighbors[v].Add(u);
edges.Add((v, u));
edgeToEdgeData.Add((v, u), edgeData);
}
2019-10-24 01:05:28 +00:00
public bool Exists(TNode v, TNode u)
{
CheckNodes(v, u);
return edges.Contains((v, u));
}
public TEdgeData EdgeData(TNode v, TNode u)
{
CheckEdge(v, u);
return edgeToEdgeData[(v, u)];
}
protected void CheckEdge(TNode v, TNode u)
{
CheckNodes(v, u);
if (!Exists(v, u)) { throw new ArgumentException($"Edge between vertex {v} and vertex {u} does not exist in the graph"); }
}
2019-10-24 01:28:14 +00:00
public override void Clear()
{
base.Clear();
edges.Clear();
edgeToEdgeData.Clear();
}
2019-10-24 01:05:28 +00:00
}
2020-02-21 02:43:25 +00:00
}