/// <summary> /// Generates all the possible edges for given nodes and returns them. /// </summary> /// <param name="listNodes">The list nodes.</param> /// <param name="listEdges">[out]The list edges.</param> /// <returns></returns> public static bool generateEdgeList(SortedNodeList listNodes, out SortedEdgeList listEdges) { bool bRet = false; SortedEdgeList l_listEdges = new SortedEdgeList(); UInt32 nEdgeID = 0; for(Int32 nFrom = 0; nFrom < listNodes.Count; ++nFrom) { for (Int32 nTo = nFrom+1; nTo < listNodes.Count; ++nTo) { // make sure it is sorted by distance. GraphEdge e = new GraphEdge(++nEdgeID, listNodes[nFrom], listNodes[nTo], 0); l_listEdges.AddSorted(e); bRet = true; } } listEdges = l_listEdges; return bRet; }
/// <summary> /// Runs the KRUSKAL algorithm. It takes parameters from the graph. /// it applies the KRUSKAL algorithm on the edges and finally stores /// the Minimal list of edges in the graph so that it becomes a tree. /// I have preferred to use Graph data structres over tree, It allows /// me to store more data than tree. /// </summary> /// <param name="listEdges">list of KRUSKAL Edges.</param> /// <returns></returns> public bool runKruskal(out SortedEdgeList listEdges) { bool bRet = false; // 1. an empty list of edges, this shall be filled. SortedEdgeList l_listEdges = new SortedEdgeList(); // we already have sorted list, our DataStruct handles it. // we want to update our edges link in graphnodes hence cleaning // existing links. foreach (GraphNode n in m_listNodes) { n.m_listEdge.Clear(); } // 2 lets generate all possible list of edges (n!) SortedEdgeList l_AllPossibleEdges = new SortedEdgeList(); Util.generateEdgeList(m_listNodes, out l_AllPossibleEdges); // 3. foreach edge @ graph (existing links) foreach (GraphEdge e in l_AllPossibleEdges) { // check if it connects two nodes. do a DFS search. // essentially this shall choose smallest edges first. // each of node contains edges. so hasPathDFS() checks for any // feasible path between those edges. // if no path exists, than this link connects them // so I am adding it. if (Util.hasPathDFS(e.m_nodeFrom, e.m_nodeTo) == false) { // add the edge in the list l_listEdges.AddSorted(e); // add edges in from and to e.m_nodeFrom.addEdge(e); e.m_nodeTo.addEdge(e); bRet = true; } } // 4. assign it to out parameter listEdges = l_listEdges; return bRet; }