2019-10-24 01:05:28 +00:00
|
|
|
using System.Collections.Generic;
|
2019-10-24 01:28:14 +00:00
|
|
|
using Collections.Pooled;
|
2019-10-24 01:05:28 +00:00
|
|
|
|
|
|
|
namespace MoonTools.Core.Graph
|
|
|
|
{
|
|
|
|
abstract public class Graph<TNode, TEdgeData> where TNode : System.IEquatable<TNode>
|
|
|
|
{
|
|
|
|
protected HashSet<TNode> nodes = new HashSet<TNode>();
|
2019-10-24 01:28:14 +00:00
|
|
|
protected Dictionary<TNode, PooledSet<TNode>> neighbors = new Dictionary<TNode, PooledSet<TNode>>();
|
2019-10-24 01:05:28 +00:00
|
|
|
|
|
|
|
public IEnumerable<TNode> Nodes => nodes;
|
|
|
|
|
|
|
|
public int Order => nodes.Count;
|
|
|
|
|
|
|
|
public void AddNode(TNode node)
|
|
|
|
{
|
|
|
|
if (!Exists(node))
|
|
|
|
{
|
|
|
|
nodes.Add(node);
|
2019-10-24 01:28:14 +00:00
|
|
|
neighbors.Add(node, new PooledSet<TNode>(ClearMode.Always));
|
2019-10-24 01:05:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public void AddNodes(params TNode[] nodes)
|
|
|
|
{
|
|
|
|
foreach (var node in nodes)
|
|
|
|
{
|
|
|
|
AddNode(node);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public int Degree(TNode node)
|
|
|
|
{
|
|
|
|
CheckNodes(node);
|
|
|
|
return neighbors[node].Count;
|
|
|
|
}
|
|
|
|
|
|
|
|
public bool Exists(TNode node)
|
|
|
|
{
|
|
|
|
return nodes.Contains(node);
|
|
|
|
}
|
|
|
|
|
|
|
|
public IEnumerable<TNode> Neighbors(TNode node)
|
|
|
|
{
|
|
|
|
CheckNodes(node);
|
|
|
|
return neighbors[node];
|
|
|
|
}
|
|
|
|
|
|
|
|
protected void CheckNodes(params TNode[] givenNodes)
|
|
|
|
{
|
|
|
|
foreach (var node in givenNodes)
|
|
|
|
{
|
|
|
|
if (!Exists(node))
|
|
|
|
{
|
|
|
|
throw new System.ArgumentException($"Vertex {node} does not exist in the graph");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-24 01:28:14 +00:00
|
|
|
public virtual void Clear()
|
|
|
|
{
|
|
|
|
nodes.Clear();
|
|
|
|
neighbors.Clear();
|
|
|
|
}
|
2019-10-24 01:05:28 +00:00
|
|
|
}
|
|
|
|
}
|