/// <summary> /// Kruskal algorithm /// </summary> /// <returns>return the min span tree for this grpah</returns> public MatrixGraph Kruskal() { double[][] result = GetNonEdgeGraph(); List <EdgeNode> edgeNodes = new List <EdgeNode>(count); for (int i = 0; i < count; i++) { for (int j = 0; j < count; j++) { double length = matrix[i][j]; if (length != maxDistance) { EdgeNode edgeNode = new EdgeNode(i, j, length); edgeNodes.Add(edgeNode); } } } edgeNodes.Sort(); int addEdgeNumber = 0; DisjointSet set = new DisjointSet(count); for (int i = 0; i < edgeNodes.Count; i++) { int sourceIndex = edgeNodes[i].SourceIndex; int destinationIndex = edgeNodes[i].DestinationIndex; if (!set.IsInSameSet(sourceIndex, destinationIndex)) { result[sourceIndex][destinationIndex] = edgeNodes[i].Length; set.Union(sourceIndex, destinationIndex); addEdgeNumber++; } if (addEdgeNumber == count) { break; } } if (addEdgeNumber != count) { throw new InvalidOperationException("The graph isn't connected!"); } return(new MatrixGraph(result, maxDistance)); }
public int CompareTo(EdgeNode other) { return(length.CompareTo(other.length)); }