You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is question requires a minimum span tree(MST) algothrim.
9
-
I choose to use Prim's algothrim because it is similar to Dijkstra's algorithm over Kruskal's algorithm.
8
+
This is question requires a minimum spanning tree(MST) algorithm.
9
+
I choose to use Prim's algorithm because it is similar to Dijkstra's algorithm over Kruskal's algorithm, both are greedy algorithms.
10
10
Knowing one will help you in learning the other.
11
11
12
12
The idea with Prim's is to utilize a heap of vertices and an adjacent list.
13
13
The resulting MST cannot produce a cycle due to the method of selecting an edge of an unvisited vertex.
14
14
To select an edge, we use the heap sorted by the cost or weight of the edge.
15
-
Each time we pop from the heap, we mark that vetrex as visited and add it's neighboring vertices' edges to the heap.
15
+
Each time we pop from the heap, we mark that vertex as visited and add it's neighboring vertices' edges to the heap.
16
16
17
17
The pseudocode could be represented as such:
18
18
1. Select an arbitrary vertex to start with and add its neighboring vertices to the heap.
@@ -22,48 +22,44 @@ The pseudocode could be represented as such:
22
22
- Add the selected vertex to the visited vertices.
23
23
- Add selected vertex's neighboring edges of unvisited vertices into the heap.
24
24
25
-
Since we are sorting based on vertices, the sorting will take log(V) run-time.
26
-
However, we have to sort this based on number of vertices or edges because we can be given a graph of islands or nodes that have edges to all nodes.
27
-
That is why its O((V+E) log(V)) run-time.
25
+
As of the time of writing this, Python 3.7 doesn't have an adaptable priority queue implementation.
26
+
So this is why this version of Prim's runs at O(N^2) time.
27
+
This example is more of a lazy heap implementation.
28
+
If we were to use an adaptable priority queue, we would see O(MlogN) run-time.
29
+
This is because we will only have at most N cities in the heap, no duplicates.
30
+
There would be a feature to update a specific city's cost in the heap and bubble up and down the heap to maintain the heap property.
31
+
With an adaptable priority queue, there would be no need to use a visited set.
32
+
33
+
To read more about adaptable priority queues, check out [Data Structures and Algorithms in Python 1st Edition](https://www.amazon.com/Structures-Algorithms-Python-Michael-Goodrich/dp/1118290275).
0 commit comments