Skip to content

Instantly share code, notes, and snippets.

@GER-NaN
Created December 30, 2016 19:59
Show Gist options
  • Save GER-NaN/055abdb5647474cc4f9ed0ede04b7364 to your computer and use it in GitHub Desktop.
Save GER-NaN/055abdb5647474cc4f9ed0ede04b7364 to your computer and use it in GitHub Desktop.
Graph class
/*
https://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx
An Extensive Examination of Data Structures Using C# 2.0
Visual Studio 2005
Scott Mitchell
4GuysFromRolla.com
Update January 2005
*/
public class Graph<T> : IEnumerable<T>
{
private NodeList<T> nodeSet;
public Graph() : this(null) {}
public Graph(NodeList<T> nodeSet)
{
if (nodeSet == null)
this.nodeSet = new NodeList<T>();
else
this.nodeSet = nodeSet;
}
public void AddNode(GraphNode<T> node)
{
// adds a node to the graph
nodeSet.Add(node);
}
public void AddNode(T value)
{
// adds a node to the graph
nodeSet.Add(new GraphNode<T>(value));
}
public void AddDirectedEdge(GraphNode<T> from, GraphNode<T> to, int cost)
{
from.Neighbors.Add(to);
from.Costs.Add(cost);
}
public void AddUndirectedEdge(GraphNode<T> from, GraphNode<T> to, int cost)
{
from.Neighbors.Add(to);
from.Costs.Add(cost);
to.Neighbors.Add(from);
to.Costs.Add(cost);
}
public bool Contains(T value)
{
return nodeSet.FindByValue(value) != null;
}
public bool Remove(T value)
{
// first remove the node from the nodeset
GraphNode<T> nodeToRemove = (GraphNode<T>) nodeSet.FindByValue(value);
if (nodeToRemove == null)
// node wasn't found
return false;
// otherwise, the node was found
nodeSet.Remove(nodeToRemove);
// enumerate through each node in the nodeSet, removing edges to this node
foreach (GraphNode<T> gnode in nodeSet)
{
int index = gnode.Neighbors.IndexOf(nodeToRemove);
if (index != -1)
{
// remove the reference to the node and associated cost
gnode.Neighbors.RemoveAt(index);
gnode.Costs.RemoveAt(index);
}
}
return true;
}
public NodeList<T> Nodes
{
get
{
return nodeSet;
}
}
public int Count
{
get { return nodeSet.Count; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment