简体   繁体   中英

Alternate way to find minimum cost of connecting a graph

I came across a classic Kruskals problem, where given an undirected graph and set of weights between edges, I was asked to find the minimum cost required to connect the edges. I wasnt too familiar with Kruskals algorithm, so I came up with my own solution. However, it came up short on a few test cases. Here's the algorithm: 1- Sort the edges based on weights. Used a Priority Queue of type Node.Node consists of src, dest and weight.

2- Tracking the nodes visited using a boolean array of size N, where N is the no of nodes.

2- Poll the Priority Queue (Remove head). If either the src or dest aren't visited, add the weight to the solution, and mark both of them as visited.

Can somebody help me out here as to why this algorithm comes up short? Logically, it seems to me that the visited array should keep track of ensuring that there are no cycles, as I'm only adding it to the solution if either src or dest are unvisited.

At some point, you are usually going to need to add an edge to the solution with both endpoints visited. For example, consider the following graph:

A --1-- B
|
|
3
|
|
C --2-- D

After adding edges AB and CD to the solution, your algorithm will refuse to add AC, because both A and C have been visited.

Kruskal's algorithm refuses to add an edge to the solution if the endpoints are already in the same tree, which is very different from your condition.

You can use prims algorithm to find MST. It is easy than Kruskal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM