{"id":22513427,"url":"https://github.com/emahtab/connecting-cities-with-minimum-cost","last_synced_at":"2026-03-19T23:02:59.082Z","repository":{"id":79525365,"uuid":"440743043","full_name":"eMahtab/connecting-cities-with-minimum-cost","owner":"eMahtab","description":"Minimum Spanning Tree","archived":false,"fork":false,"pushed_at":"2024-11-15T16:03:25.000Z","size":44,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-02T03:19:11.499Z","etag":null,"topics":["graph","kruskals-algorithm","leetcode","minimum-spanning-tree","prims-algorithm"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/eMahtab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-12-22T05:26:30.000Z","updated_at":"2024-11-15T16:03:43.000Z","dependencies_parsed_at":"2023-05-10T17:00:38.319Z","dependency_job_id":null,"html_url":"https://github.com/eMahtab/connecting-cities-with-minimum-cost","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fconnecting-cities-with-minimum-cost","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fconnecting-cities-with-minimum-cost/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fconnecting-cities-with-minimum-cost/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/eMahtab%2Fconnecting-cities-with-minimum-cost/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/eMahtab","download_url":"https://codeload.github.com/eMahtab/connecting-cities-with-minimum-cost/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":245950637,"owners_count":20699102,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["graph","kruskals-algorithm","leetcode","minimum-spanning-tree","prims-algorithm"],"created_at":"2024-12-07T03:12:20.124Z","updated_at":"2026-01-07T01:42:45.343Z","avatar_url":"https://github.com/eMahtab.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Connecting cities with minimum cost\n## https://leetcode.com/problems/connecting-cities-with-minimum-cost\n\nThere are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.\n\nReturn the minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1,\n\nThe cost is the sum of the connections' costs used.\n\n![Connecting cities with minimum cost](example.JPG?raw=true)\n\n\n# Implementation 1 : Minimum Spanning Tree (Prim's Algorithm)\n```java\nclass Solution {\n    class Edge {\n        int v1, v2, cost;\n        Edge(int v1, int v2, int cost){\n            this.v1 = v1;\n            this.v2 = v2;\n            this.cost = cost;\n        }\n    }\n    public int minimumCost(int n, int[][] connections) {\n        Map\u003cInteger,List\u003cEdge\u003e\u003e map = new HashMap\u003c\u003e();\n        for(int[] connection : connections) {\n            int v1 = connection[0] - 1;\n            int v2 = connection[1] - 1;\n            map.putIfAbsent(v1, new ArrayList\u003cEdge\u003e());\n            map.get(v1).add(new Edge(v1,v2,connection[2]));\n            \n            map.putIfAbsent(v2, new ArrayList\u003cEdge\u003e());\n            map.get(v2).add(new Edge(v2,v1,connection[2]));\n        }\n        \n        boolean[] visited = new boolean[n];\n        PriorityQueue\u003cint[]\u003e pq = new PriorityQueue\u003c\u003e((v1, v2) -\u003e v1[1] - v2[1]);\n        pq.add(new int[]{0,0});\n        \n        int minCost = 0;\n        int count = 0;\n        while(!pq.isEmpty()) {\n            int[] vertex = pq.remove();\n            if(!visited[vertex[0]]) {\n               minCost += vertex[1]; \n               visited[vertex[0]] = true;\n               count++; \n                \n               // add unvisited neighbors of current vertex to priority queue\n               List\u003cEdge\u003e edges = map.get(vertex[0]);\n               for(Edge edge : edges) {\n                   if(!visited[edge.v2]) {\n                       pq.add(new int[]{edge.v2, edge.cost});\n                   }\n               } \n            }\n        }\n        return count == n ? minCost : -1;\n    }\n}\n```\n\n# Implementation 1a : Without creating Edge, a little more succinct code\n```java\nclass Solution {\n    public int minimumCost(int n, int[][] connections) {\n        Map\u003cInteger,List\u003cint[]\u003e\u003e graph = new HashMap\u003c\u003e();\n        for(int i= 0; i \u003c n; i++)\n            graph.put(i, new ArrayList\u003c\u003e());\n        for(int[] connection : connections) {\n            int u = connection[0]-1, v = connection[1]-1, cost = connection[2];\n            graph.get(u).add(new int[]{v, cost});\n            graph.get(v).add(new int[]{u, cost});\n        }\n\n        PriorityQueue\u003cint[]\u003e pq = new PriorityQueue\u003c\u003e((n1, n2) -\u003e n1[1] - n2[1]);\n        pq.add(new int[]{0, 0});\n        int minCost = 0;\n        Set\u003cInteger\u003e visited = new HashSet\u003c\u003e();\n        while(!pq.isEmpty()) {\n            int[] node = pq.remove();\n            if(visited.contains(node[0])) continue;\n            minCost += node[1];\n            visited.add(node[0]);\n            for(int[] neighbor : graph.get(node[0])) {\n                if(!visited.contains(neighbor[0]))\n                   pq.add(neighbor);\n            }\n        }\n        return visited.size() == n ? minCost : -1;\n    }\n}\n```\n# Implementation 2 : Minimum Spanning Tree (Kruskal's Algorithm using Union Find)\n```java\nclass Solution {\n    \n    public int minimumCost(int n, int[][] connections) {\n        int minCost = 0;\n        int edgesConnected = 0;\n        Arrays.sort(connections, (e1, e2) -\u003e e1[2] - e2[2]);\n        int[] parents = new int[n];\n        int[] rank = new int[n];\n        for(int i = 0; i \u003c n; i++) {\n            parents[i] = i;\n            rank[i] = 1;\n        }\n        \n        for(int[] connection : connections) {\n            boolean flag = union(connection[0] - 1, connection[1] - 1, parents, rank);\n            if(flag) {\n                minCost += connection[2];\n                edgesConnected++;\n            }        \n        }\n        \n        return edgesConnected == n - 1 ? minCost : -1;\n    }\n    \n    private boolean union(int v1, int v2, int[] parents, int[] rank) {\n        int leader1 = find(v1, parents);\n        int leader2 = find(v2, parents);\n        if(leader1 != leader2) {\n            if(rank[leader1] \u003e rank[leader2]) {\n                parents[leader2] = leader1;\n            } else if(rank[leader2] \u003e rank[leader1]) {\n                parents[leader1] = leader2;\n            } else {\n                parents[leader2] = leader1;\n                rank[leader1]++;\n            }\n            return true;\n        } else {\n            return false;\n        }\n    }\n    \n    private int find(int v, int[] parents) {\n        if(parents[v] == v)\n            return parents[v];\n        parents[v] = find(parents[v], parents);\n        return parents[v];\n    }\n}\n```\n\n# References :\n1. Prim's Algorithm : https://www.youtube.com/watch?v=Vw-sktU1zmc (Hindi, very good explanation)\n2. Kruskal's Algorithm : https://www.youtube.com/watch?v=YU3Bvek4wjs (Hindi, very good explanation)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fconnecting-cities-with-minimum-cost","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femahtab%2Fconnecting-cities-with-minimum-cost","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femahtab%2Fconnecting-cities-with-minimum-cost/lists"}