public int MinCostConnectPoints(int[][] points) { var n = points.Length; var l = new List <Edge>(n * n); for (var i = 0; i < n - 1; i++) { for (var j = i + 1; j < n; j++) { var length = Math.Abs(points[i][0] - points[j][0]) + Math.Abs(points[i][1] - points[j][1]); l.Add(new Edge(i, j, length)); } } var orderList = l.OrderBy(i => i.Length); var res = 0; var uf = new UF(n); foreach (var listItem in orderList) { var fx = uf.Find(listItem.X); var fy = uf.Find(listItem.Y); if (fx != fy) { res += listItem.Length; uf.Union(fx, fy); } } return(res); }
private readonly double _weight; // weight of MST /// <summary> /// Compute a minimum spanning tree (or forest) of an edge-weighted graph. /// </summary> /// <param name="g">g the edge-weighted graph</param> public BoruvkaMST(EdgeWeightedGraph g) { var uf = new UF(g.V); // repeat at most log V times or until we have V-1 edges for (var t = 1; t < g.V && _mst.Size() < g.V - 1; t = t + t) { // foreach tree in forest, find closest edge // if edge weights are equal, ties are broken in favor of first edge in G.edges() var closest = new EdgeW[g.V]; foreach (var e in g.Edges()) { int v = e.Either(), w = e.Other(v); int i = uf.Find(v), j = uf.Find(w); if (i == j) { continue; // same tree } if (closest[i] == null || Less(e, closest[i])) { closest[i] = e; } if (closest[j] == null || Less(e, closest[j])) { closest[j] = e; } } // add newly discovered edges to MST for (var i = 0; i < g.V; i++) { var e = closest[i]; if (e != null) { int v = e.Either(), w = e.Other(v); // don't add the same edge twice if (!uf.Connected(v, w)) { _mst.Add(e); _weight += e.Weight; uf.Union(v, w); } } } } // check optimality conditions //assert check(G); }