// Kruskal algorithm calculate minimum spanning tree on the input undirected graph
Kruskal algorithm calculate minimum spanning tree on the input undirected graph
// Kruskal algorithm calculate minimum spanning tree on the input undirected graph
func Kruskal(g weightedgraph.WeightedGraph) (MinSpanningTree, error) {
	mst := MinSpanningTree{[]graph.EdgeID{}, g}
	edges := edgeWithWeightArray{}
	g.IterateEdges(func(edge graph.EdgeID) {
		weight, _ := g.Weight(edge.From, edge.To) 
		edges = append(edges, edgeWithWeight{edge, weight})
	})
	sort.Sort(edges) 
	nodesSets := sets{map[int]map[graph.NodeID]struct{}{}, 0}
	for _, e := range edges {
		if !nodesSets.nodesInSameSet(e.From, e.To) {
			nodesSets.union(e.From, e.To)
			mst.edges = append(mst.edges, e.EdgeID)
		}
	}
	return mst, nil
}
func Kruskal ( g weightedgraph . WeightedGraph ) ( MinSpanningTree , error ) { mst := MinSpanningTree { [ ] graph . EdgeID { } , g } edges := edgeWithWeightArray { } g . IterateEdges ( func ( edge graph . EdgeID ) { weight , _ := g . Weight ( edge . From , edge . To ) edges = append ( edges , edgeWithWeight { edge , weight } ) } ) sort . Sort ( edges ) nodesSets := sets { map [ int ] map [ graph . NodeID ] struct { } { } , 0 } for _ , e := range edges { if ! nodesSets . nodesInSameSet ( e . From , e . To ) { nodesSets . union ( e . From , e . To ) mst . edges = append ( mst . edges , e . EdgeID ) } } return mst , nil }
Kruskal algorithm calculate minimum spanning tree on the input undirected graph
Kruskal algorithm calculate minimum spanning tree on the input undirected graph
// collect all edges with weight //TODO: check err if necessary // sort by weight increasing //MAKE-SETS //TODO: should be a better way to implement the sets