using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; namespace DataStructures.AdjacencyList { [Serializable] public class WeightedAdjacencyList where T : class { private readonly Dictionary>> dict; public IList Vertices { get { return dict.Keys.ToList(); } } public int Count { get { return dict.Count; } } public WeightedAdjacencyList() { dict = new Dictionary>>(); } public WeightedAdjacencyList(int capacity) { Contract.Requires(capacity > 0); dict = new Dictionary>>(capacity); } public void AddVertex(T vertex) { Contract.Requires(vertex != null); if(dict.ContainsKey(vertex)) { return; } dict[vertex] = new HashSet>(); } public Node[] AddEdge(T vertex1, T vertex2, double weight) { Contract.Requires(vertex1 != null); Contract.Requires(vertex2 != null); //need to return the nodes in order to allow the search for them later on var weightedEdgeNodes = new Node[2]; if(!dict.ContainsKey(vertex1)) { dict[vertex1] = new HashSet>(); } if(!dict.ContainsKey(vertex2)) { dict[vertex2] = new HashSet>(); } weightedEdgeNodes[0] = new Node(vertex2, weight); weightedEdgeNodes[1] = new Node(vertex1, weight); dict[vertex1].Add(weightedEdgeNodes[0]); dict[vertex2].Add(weightedEdgeNodes[1]); return weightedEdgeNodes; } public bool IsNeighbourOf(T vertex, Node neighbour) { Contract.Requires(vertex != null); Contract.Requires(neighbour != null); return dict.ContainsKey(vertex) && dict[vertex].Contains(neighbour); } public IList GetAllWeights(T vertex) { Contract.Requires(vertex != null); return dict.ContainsKey(vertex) ? dict[vertex].Select(n =>n.weight).ToList() : new List(); } public IList> GetNeighbours(T vertex) { Contract.Requires(vertex != null); return dict.ContainsKey(vertex)? dict[vertex].Select(n => new Tuple(n.item, n.weight)).ToList() : new List>(); } public class Node where T : class { public T item; public readonly double weight; public Node(T item, double weight) { this.item = item; this.weight = weight; } public bool Equals(T item) { return this.item.Equals(item); } public bool Equals(Node node) { return this.item.Equals(node.item) && (weight == node.weight); } public override bool Equals(object obj) { if(obj is T) { return item.Equals(obj as T); } if(obj is Node) { return Equals(obj as Node); } return false; } public override int GetHashCode() { return item.GetHashCode() ^ int.Parse(weight.ToString()); } } } }