{"id":7367,"date":"2020-09-13T00:22:16","date_gmt":"2020-09-13T07:22:16","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=7367"},"modified":"2020-09-13T00:46:41","modified_gmt":"2020-09-13T07:46:41","slug":"leetcode-1584-min-cost-to-connect-all-points","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-1584-min-cost-to-connect-all-points\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1584. Min Cost to Connect All Points"},"content":{"rendered":"\n<p>You are given an array&nbsp;<code>points<\/code>&nbsp;representing integer coordinates of some points on a 2D-plane, where&nbsp;<code>points[i] = [x<sub>i<\/sub>, y<sub>i<\/sub>]<\/code>.<\/p>\n\n\n\n<p>The cost of connecting two points&nbsp;<code>[x<sub>i<\/sub>, y<sub>i<\/sub>]<\/code>&nbsp;and&nbsp;<code>[x<sub>j<\/sub>, y<sub>j<\/sub>]<\/code>&nbsp;is the&nbsp;<strong>manhattan distance<\/strong>&nbsp;between them:&nbsp;<code>|x<sub>i<\/sub>&nbsp;- x<sub>j<\/sub>| + |y<sub>i<\/sub>&nbsp;- y<sub>j<\/sub>|<\/code>, where&nbsp;<code>|val|<\/code>&nbsp;denotes the absolute value of&nbsp;<code>val<\/code>.<\/p>\n\n\n\n<p>Return&nbsp;<em>the minimum cost to make all points connected.<\/em>&nbsp;All points are connected if there is&nbsp;<strong>exactly one<\/strong>&nbsp;simple path between any two points.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/08\/26\/d.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> points = [[0,0],[2,2],[3,10],[5,2],[7,0]]\n<strong>Output:<\/strong> 20\n<strong>Explanation:\n<\/strong>\nWe can connect the points as shown above to get the minimum cost of 20.\nNotice that there is a unique path between every pair of points.\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> points = [[3,12],[-2,5],[-4,1]]\n<strong>Output:<\/strong> 18\n<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> points = [[0,0],[1,1],[1,0],[-1,1]]\n<strong>Output:<\/strong> 4\n<\/pre>\n\n\n\n<p><strong>Example 4:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> points = [[-1000000,-1000000],[1000000,1000000]]\n<strong>Output:<\/strong> 4000000\n<\/pre>\n\n\n\n<p><strong>Example 5:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> points = [[0,0]]\n<strong>Output:<\/strong> 0\n<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>1 &lt;= points.length &lt;= 1000<\/code><\/li><li><code>-10<sup>6<\/sup>&nbsp;&lt;= x<sub>i<\/sub>, y<sub>i<\/sub>&nbsp;&lt;= 10<sup>6<\/sup><\/code><\/li><li>All pairs&nbsp;<code>(x<sub>i<\/sub>, y<sub>i<\/sub>)<\/code>&nbsp;are distinct.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: Minimum Spanning Tree<\/strong><\/h2>\n\n\n\n<p>Kruskal&#8217;s algorithm <br>Time complexity: O(n^2logn) <br>Space complexity: O(n^2)<br>using vector of vector, array, pair of pair, or tuple might lead to TLE&#8230;<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\nstruct Edge {\n  int cost;\n  int x;\n  int y;\n  bool operator<(const Edge&#038; e) const { return cost < e.cost; }\n};\nclass Solution {\npublic:\n  int minCostConnectPoints(vector<vector<int>>& points) {\n    const int n = points.size();\n    vector<Edge> edges(n * (n - 1) \/ 2); \/\/ {cost, i, j}\n    for (int i = 0, idx = 0; i < n; ++i)\n      for (int j = i + 1; j < n; ++j)\n        edges[idx++] = {abs(points[i][0] - points[j][0]) + \n                        abs(points[i][1] - points[j][1]), i, j};\n    std::sort(begin(edges), end(edges));\n    vector<int> p(n); \n    std::iota(begin(p), end(p), 0);\n    vector<int> rank(n, 0);\n    int ans = 0;\n    int count = 0;\n    for (const auto& e : edges) {          \n      int rx = find(p, e.x);\n      int ry = find(p, e.y);\n      if (rx == ry) continue;\n      ans += e.cost;\n      if (rank[rx] < rank[ry]) swap(rx, ry);\n      p[rx] = ry;\n      rank[ry] += rank[rx] == rank[ry];\n      if (++count == n - 1) break;\n    }\n    return ans;\n  }\nprivate:\n  int find(vector<int>& p, int x) const {   \n    while (p[x] != x) {\n      int tp = p[x];\n      p[x] = p[p[x]];\n      x = tp;\n    }\n    return x;\n  }\n};\n<\/pre>\n<\/div><\/div>\n\n\n\n<p>Prim&#8217;s Algorithm <br>ds[i] := min distance from i to <strong>ANY<\/strong> nodes in the tree.<\/p>\n\n\n\n<p>Time complexity: O(n^2) Space complexity: O(n)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"c++\">\nclass Solution {\npublic:\n  int minCostConnectPoints(vector<vector<int>>& points) {\n    const int n = points.size();\n    auto dist = [](const vector<int>& pi, const vector<int>& pj) {\n      return abs(pi[0] - pj[0]) + abs(pi[1] - pj[1]);\n    };\n    vector<int> ds(n, INT_MAX);  \n    for (int i = 1; i < n; ++i)\n      ds[i] = dist(points[0], points[i]);\n    \n    int ans = 0;\n    for (int i = 1; i < n; ++i) {\n      auto it = min_element(begin(ds), end(ds));\n      const int v = distance(begin(ds), it);\n      ans += ds[v];      \n      ds[v] = INT_MAX; \/\/ done\n      for (int i = 0; i < n; ++i) {\n        if (ds[i] == INT_MAX) continue;\n        ds[i] = min(ds[i], dist(points[i], points[v]));\n      }        \n    }\n    return ans;\n  }\n};\n<\/pre>\n<\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>You are given an array&nbsp;points&nbsp;representing integer coordinates of some points on a 2D-plane, where&nbsp;points[i] = [xi, yi]. The cost of connecting two points&nbsp;[xi, yi]&nbsp;and&nbsp;[xj, yj]&nbsp;is&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[76],"tags":[77,177,533],"class_list":["post-7367","post","type-post","status-publish","format-standard","hentry","category-graph","tag-graph","tag-medium","tag-mst","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7367","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=7367"}],"version-history":[{"count":5,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7367\/revisions"}],"predecessor-version":[{"id":7373,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/7367\/revisions\/7373"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=7367"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=7367"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=7367"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}