Minimum spanning tree
A minimum spanning tree is a spanning subgraph of a weighted graph that includes every vertex, remains connected, contains no cycles, and has the smallest possible sum of edge weights among all such subgraphs.
ByteQuest · YouTube · 3:34
This 120-second clip introduces minimum spanning trees, demonstrates Prim's algorithm on a small weighted graph, explains why a spanning tree has V - 1 edges, and begins showing a Python implementation with heapq. The worked example starts at vertex A and selects edges AB, BD, DC, and AF, yielding total weight 8. The final seconds transition from the visual graph to code, but the full function body is not shown within this excerpt. This 94-second clip walks through a Python implementation of Prim's algorithm for a weighted graph stored as an adjacency list, then analyzes its asymptotic costs. The first half highlights the code in execution order: initialize a priority queue, visited set, MST edge list, and total cost; mark the start vertex; push its incident edges; repeatedly pop the minimum-weight candidate; accept it only if the destination is unvisited; record the edge, update the cost, and expand the frontier; finally return the MST edges and total cost. The second half switches to a slide that derives time complexity as `` and space complexity as ``. One notable detail is that the narration says all connected edges are pushed, while the visible code filters neighbors already in `visited` before pushing.
Use the learning inspector for key ideas and moments, or open the reading tabs for the complete notes.
Generated from the video's visuals and explanation; not verbatim speech.
The clip opens on a weighted undirected graph with labeled vertices A, B, C, D, and F. While this picture stays on screen, the narration defines a minimum spanning tree as a subset of the graph that connects all vertices, keeps the graph connected, avoids cycles, and minimizes total edge weight.
The same graph remains visible as the speaker introduces Prim's algorithm. The method is described greedily: choose a starting vertex, then repeatedly add the smallest-weight edge that expands the current tree without breaking connectivity or creating a cycle.
The demonstration begins at vertex A. The animation marks A as part of the current tree and highlights the boundary edges from A. Among these, AB of weight 2 is chosen first and turns red, adding B to the tree.
With A and B now in the tree, the animation highlights the next set of candidate edges crossing out of the tree. The narrator explains that the minimum-cost admissible edge is BD with weight 2, so BD is added and D joins the tree.
The process repeats from the enlarged tree {A, B, D}. The cheapest boundary edge is DC with weight 1, so DC is selected and C becomes part of the tree.
Finally, from {A, B, D, C}, the algorithm selects AF with weight 3. Once F is added, every displayed vertex belongs to the tree, so the construction stops. The resulting tree edges are AB, BD, DC, and AF.
The non-tree edges disappear, leaving only the red spanning tree. Beside it, the text "V - 1 Edges" appears. The narration explains the structural reason: fewer than V - 1 edges would leave some vertex disconnected, while more than V - 1 edges would force a cycle.
The screen switches to Python code. The visible portion imports `heapq`, defines `prims_algorithm(graph, start)`, initializes a priority queue, a visited set, an MST edge list, and a total cost, then marks the start vertex visited and pushes its adjacent edges onto the heap. The clip ends while the main loop is only partly shown.
The clip opens on a Python function `prims_algorithm(graph, start)` and immediately identifies the four pieces of state needed to run Prim's algorithm. A green box frames `priority_queue = []`, `visited = set()`, `mst_edges = []`, and `total_cost = 0`. Mathematically, these correspond to the frontier of candidate edges, the set of vertices already absorbed into the tree, the output edge set, and the objective value being minimized.
The highlight moves to the seeding step. The code marks the chosen root with `visited.add(start)` and then iterates over `graph[start]`, pushing tuples `(weight, start, neighbor)` into the heap. This establishes the first cut between visited and unvisited vertices and populates the frontier with exactly the edges crossing that cut. The narration also states the structural assumption that `graph` is an adjacency list.
Next the main greedy loop is shown. While `priority_queue` is nonempty, the algorithm executes `weight, u, v = heapq.heappop(priority_queue)`, extracting the currently cheapest candidate edge. The condition `if v not in visited:` implements the essential test of Prim's method: accept the edge only when it crosses from the visited side of the cut to an unvisited vertex. If `v` is already visited, the edge is discarded as internal to the current tree.
When the test succeeds, the code performs three updates in sequence: `visited.add(v)`, `mst_edges.append((u, v))`, and `total_cost += weight`. These lines mirror the mathematical definition of growing a minimum spanning tree one vertex at a time while accumulating total weight. The algorithm then scans `graph[v]` and pushes only those `(weight, v, neighbor)` pairs whose `neighbor` is not yet visited, thereby refreshing the frontier after the cut has expanded.
After the loop terminates, the function returns `mst_edges, total_cost`. The first object is the explicit edge list of the tree, and the second is the sum of its edge weights. The clip does not discuss the connectivity precondition, but the returned structure is intended to represent a minimum spanning tree when the input graph is connected.
The scene changes to a slide titled `TIME COMPLEXITY`. It first shows `` for scanning edges, then appends `` for heap operations, and finally simplifies the sum to ``. The reasoning is that each edge enters the priority queue about once, and each heap insertion or extraction costs logarithmic time in the number of vertices under the binary-heap model used here.
A second heading, `SPACE COMPLEXITY`, is added below. The slide accumulates `` for the adjacency-list graph, `` for the visited set, `` for the priority queue, and `` for the MST edge list, then collapses the total to ``. This makes explicit that memory is dominated by storing the graph itself plus linear-size auxiliary structures, while runtime is dominated by logarithmic heap operations on edges.
A minimum spanning tree is a spanning subgraph of a weighted graph that includes every vertex, remains connected, contains no cycles, and has the smallest possible sum of edge weights among all such subgraphs.
Prim's algorithm builds a minimum spanning tree from a chosen start vertex by repeatedly adding the minimum-weight edge that connects the current tree to a vertex outside it. This preserves connectivity and avoids cycles at every step.
A priority queue stores candidate boundary edges so the algorithm can quickly extract the edge of minimum weight at each iteration. In the Python sketch, `heapq` provides this min-heap behavior.
Starting from A on the displayed graph, the selected edges are AB (2), BD (2), DC (1), and AF (3). These four edges connect all displayed vertices without forming a cycle, and their total weight is 8.
Any spanning tree on V vertices has exactly V - 1 edges. If it had fewer, it could not connect all vertices; if it had more, it would contain a cycle.
The visible code defines `prims_algorithm(graph, start)`, initializes `priority_queue`, `visited`, `mst_edges`, and `total_cost`, marks `start` visited, pushes `(weight, start, neighbor)` tuples for edges out of `start`, and begins popping the minimum candidate while checking whether the destination vertex is unvisited.
The implementation starts by creating four containers with distinct roles. `priority_queue` holds candidate edges ordered by weight, `visited` records vertices already in the tree, `mst_edges` stores the accepted edges, and `total_cost` accumulates the objective value. Together they separate frontier management, membership testing, output construction, and cost accounting.
Prim's algorithm begins by choosing a root vertex, marking it visited, and inserting all incident edges into the priority queue. In the code, `visited.add(start)` is followed by a loop over `graph[start]` that pushes `(weight, start, neighbor)`. This creates the initial cut between the tree and the rest of the graph. The clip states that `graph` is an adjacency list.
The heart of the algorithm is a loop that repeatedly pops the smallest-weight edge from the heap and checks whether its endpoint is new. The code uses `weight, u, v = heapq.heappop(priority_queue)` and then `if v not in visited:`. This implements the greedy rule of always considering the cheapest edge crossing the current cut.
If the popped edge reaches an unvisited vertex, the algorithm commits that vertex to the tree, records the edge, adds its weight to the total, and inserts newly relevant outgoing edges. The visible code updates `visited`, `mst_edges`, and `total_cost`, then loops over `graph[v]` with a filter `if neighbor not in visited:` before pushing. Note that the narration says all connected edges are pushed, but the code shown filters already-visited neighbors.
Once the priority queue is empty, the function outputs the collected edge list and the accumulated weight. `mst_edges` describes the tree structure, while `total_cost` gives the minimized sum of edge weights. The clip presents this as the final result of the algorithm.
The slide decomposes runtime into edge scanning and heap operations. Iterating over edges contributes ``, while each edge is pushed about once and each heap operation costs logarithmic time, contributing ``. Since the logarithmic term dominates, the total time complexity is ``.
Memory usage is broken down by data structure. The adjacency-list graph needs ``, the visited set needs ``, the priority queue can hold up to `` edges, and the MST edge list needs ``. Summing and simplifying gives total space ``.
Explore conditions, steps and evidence. Supplementary explanations are labeled separately from content shown in the video.
The narrator says that in any minimum spanning tree there will always be exactly V minus one edges, where V is the number of vertices in the graph.
On-screen text reads "V - 1" above "Edges" beside the final red spanning tree.
V
Number of vertices in the graph.
Positive integer; in the worked example .
The narrator states that any minimum spanning tree has exactly V - 1 edges.
The displayed formula is "V - 1 Edges".
V - 1
Number of edges in a spanning tree on V vertices.
Python code shows `def prims_algorithm(graph, start):` and later uses `graph[start]`.
The narrator says the function takes the graph and the starting node as input parameters.
The exact adjacency-list data structure is not fully specified in the visible portion.
graph
Input graph representation used by the Prim implementation.
Python code shows `def prims_algorithm(graph, start):`, then `visited.add(start)` and `for neighbor, weight in graph[start]:`.
The narrator says the function takes the starting node as an input parameter.
start
Initial vertex from which Prim's algorithm begins building the tree.
Python code initializes `priority_queue = []` and uses `heapq.heappush(priority_queue, (weight, start, neighbor))` and `heapq.heappop(priority_queue)`.
Earlier narration says a priority queue can store edges so the minimum-weight edge can be retrieved quickly.
priority_queue
Min-heap storing candidate edges as tuples ordered primarily by weight.
Python code initializes `visited = set()`, then calls `visited.add(start)` and checks `if v not in visited:`.
visited
Set of vertices already included in the growing spanning tree.
Python code initializes `mst_edges = []`.
No visible line in this clip appends to `mst_edges` before the clip ends.
mst_edges
List intended to collect the selected minimum spanning tree edges.
Python code initializes `total_cost = 0`.
No visible update to `total_cost` occurs within this clip.
total_cost
Accumulator for the total weight of the selected spanning-tree edges.
Python code contains `for neighbor, weight in graph[start]:` and pushes `(weight, start, neighbor)`.
neighbor, weight
Adjacent vertex and corresponding edge weight read from the starting vertex's adjacency list.
Python code contains `weight, u, v = heapq.heappop(priority_queue)`.
weight, u, v
Popped candidate edge tuple: edge weight, source vertex, destination vertex.
The displayed code uses `graph` as the first parameter of `prims_algorithm(graph, start)` and indexes it as `graph[start]` and `graph[v]`.
At 00:24-00:27 the narrator says, "This assumes the graph is stored in an adjacency list."
graph
Input weighted graph represented as an adjacency list; each entry maps a node to its neighboring edges with weights.
Weighted graph data structure used by Prim's algorithm.
The code shows `def prims_algorithm(graph, start):` and later `visited.add(start)` and `for neighbor, weight in graph[start]:`.
At 00:17-00:23 the narrator says, "Then we add the starting node to the visited set, and push its neighboring edges along with their weights onto the priority queue."
start
The initial vertex from which Prim's algorithm begins growing the minimum spanning tree.
A vertex of the input graph.
Narrator defines a minimum spanning tree as a subset of a graph that connects all vertices with the minimum possible total edge weight, remains connected, and contains no cycles.
A weighted undirected graph with vertices A, B, C, D, F and several edges is shown while the definition is spoken.
A minimum spanning tree is a spanning subgraph of a weighted graph that includes every vertex, is connected, has no cycles, and minimizes the sum of its edge weights.
Applies to weighted graphs.
The selected subgraph must connect all vertices.
The selected subgraph must be acyclic.
The objective is minimum total edge weight.
Narrator says they will find the minimum spanning tree using Prim's algorithm, starting by selecting a vertex and progressively adding edges with the smallest weights while keeping the graph connected and cycle-free.
Prim's algorithm builds a spanning tree from a chosen start vertex by repeatedly adding the cheapest edge that expands the current tree without creating a cycle.
Requires a connected weighted graph for a spanning tree over all vertices.
Starts from one selected vertex.
Each accepted edge must connect the current tree to a new vertex.
Narrator says a priority queue can store the edges, allowing quick retrieval of the edge with the minimum weight.
In Prim's algorithm, a priority queue stores candidate edges so the next minimum-weight edge can be extracted efficiently.
Candidate edges are ordered by weight.
The queue supports fast extraction of the minimum-weight item.
Narrator states that any minimum spanning tree has exactly V - 1 edges, where V is the number of vertices.
Text "V - 1 Edges" appears next to the final tree.
For a graph with V vertices, any spanning tree, including a minimum spanning tree, contains exactly V - 1 edges.
The graph is considered with V vertices.
The subgraph is a spanning tree, i.e., connected and acyclic.
Visible Python code imports `heapq`, defines `prims_algorithm(graph, start)`, initializes `priority_queue`, `visited`, `mst_edges`, and `total_cost`, marks `start` visited, pushes start-adjacent edges, and begins popping from the heap with a `v not in visited` check.
Narrator introduces the Python code and mentions importing `heapq` to implement the priority queue and defining the function with graph and starting node inputs.
The clip ends before the full loop body and return statement are shown.
The visible code implements Prim's algorithm with a min-heap of candidate edges, a visited set for tree vertices, and placeholders for collecting MST edges and total cost.
Uses `heapq` as a min-heap priority queue.
Graph is represented so `graph[start]` yields `(neighbor, weight)` pairs.
Vertices already in the tree are tracked in `visited`.
The screen shows `priority_queue = []`, `visited = set()`, `mst_edges = []`, and `total_cost = 0` inside `def prims_algorithm(graph, start):`.
The narrator explains each variable's purpose in order from 00:02 to 00:17.
The implementation begins by creating four state containers: a priority queue for candidate edges, a visited set for vertices already in the tree, an edge list for the MST result, and a numeric accumulator for total cost. These objects separate the algorithm's frontier, membership test, output, and objective value.
The graph is weighted.
The implementation uses a min-heap priority queue.
The graph is assumed to be stored as an adjacency list.
The highlighted code is `visited.add(start)` followed by `for neighbor, weight in graph[start]: heapq.heappush(priority_queue, (weight, start, neighbor))`.
At 00:17-00:23 the narrator says the starting node is added to `visited` and its neighboring edges are pushed onto the priority queue.
At 00:24-00:27 the narrator states the graph is stored in an adjacency list.
Prim's algorithm starts by marking one vertex as already in the tree and inserting every incident edge into the priority queue. This creates the initial cut between visited and unvisited vertices and makes the next step a repeated choice of the cheapest crossing edge.
A starting vertex `start` is chosen.
`graph[start]` enumerates adjacent `(neighbor, weight)` pairs.
Edges are pushed as `(weight, start, neighbor)` so the heap orders by weight first.
The code shows `while priority_queue:` and `weight, u, v = heapq.heappop(priority_queue)` followed by `if v not in visited:`.
At 00:28-00:35 the narrator says, "as long as the priority queue is not empty, we pop the element with the lowest weight, and check if the node is already in the visited set."
The core greedy step repeatedly removes the smallest-weight edge from the priority queue and tests whether its destination vertex is still outside the tree. If the destination is already visited, the edge is discarded; otherwise it becomes the next accepted MST edge.
The heap stores candidate edges ordered by weight.
Only the destination vertex `v` is checked against `visited` in this implementation.
The highlighted block is `visited.add(v)`, `mst_edges.append((u, v))`, `total_cost += weight`, then `for neighbor, weight in graph[v]: if neighbor not in visited: heapq.heappush(priority_queue, (weight, v, neighbor))`.
At 00:36-00:47 the narrator says the node is added to `visited`, the edge is added to the MST, the total cost is updated, and all connected edges are pushed onto the priority queue.
The narration says "all the edges connected to the current node," while the visible code only pushes edges whose neighbor is not yet visited.
When the popped edge reaches an unvisited vertex, the algorithm commits that vertex to the tree, records the edge, adds its weight to the total cost, and inserts the newly available outgoing edges into the priority queue. This maintains the invariant that the heap contains candidate edges crossing from the visited set to the rest of the graph.
The popped edge `(u, v)` has `v not in visited`.
`graph[v]` provides adjacent `(neighbor, weight)` pairs.
The implementation filters neighbors already in `visited` before pushing.
The final line shown is `return mst_edges, total_cost`.
At 00:47-00:52 the narrator says, "And finally, we return the edges and the total cost of the minimum spanning tree."
After the priority queue is exhausted, the function outputs both the selected edge list and the accumulated weight. The edge list describes the tree structure, while the scalar gives the optimization objective value.
The main loop has terminated because `priority_queue` is empty.
The graph is connected enough for the traversal to produce a spanning tree; this condition is not stated in the clip.
The slide first shows `TIME COMPLEXITY` with ``, then ``, then simplifies to ``.
At 00:57-01:10 the narrator says iterating over all edges is ``, each edge can be pushed almost once, each push takes logarithmic time, and the total is ``.
The algorithm spends linear time in the number of edges to scan adjacency information, and logarithmic time per heap insertion or extraction. Since each edge may enter the priority queue about once, the dominant term is the heap-operation cost, giving overall ``.
The priority queue is implemented as a binary heap.
Each edge is inserted at most about once.
`V` denotes the number of vertices and `E` the number of edges.
The slide shows `SPACE COMPLEXITY` and builds `` before simplifying to ``.
From 01:11 to 01:33 the narrator assigns `` to the adjacency-list graph, `` to the visited set, `` to the priority queue, and `` to the MST edge list, then concludes total space is ``.
Memory use is dominated by storing the graph itself, plus auxiliary structures for visited vertices, the frontier heap, and the output edge list. Adding these terms and simplifying yields total space ``.
The graph is stored as an adjacency list.
The visited set can contain up to all vertices.
The priority queue can contain up to all edges.
The MST edge list stores at most `V - 1` edges, bounded by ``.
Narrator explicitly states the defining properties of a minimum spanning tree.
A minimum spanning tree is a subset of a graph that connects all vertices, has minimum possible total edge weight, remains connected, and contains no cycles.
The underlying graph is weighted.
The chosen subgraph spans all vertices.
For a given weighted graph, among all spanning trees, a minimum spanning tree attains the least total edge weight.
Narrator describes starting from a vertex and progressively adding the smallest-weight edges while ensuring connectivity and no cycles.
Prim's algorithm constructs a minimum spanning tree by repeatedly adding the minimum-weight edge that expands the current connected acyclic subtree to a new vertex.
The graph is connected and weighted.
A starting vertex has been chosen.
The current selected edges form a tree.
At each iteration, choose a minimum-weight admissible edge.
Narrator says any minimum spanning tree has exactly V - 1 edges.
On-screen text displays "V - 1 Edges".
In any minimum spanning tree of a graph with V vertices, there are exactly V - 1 edges.
The subgraph is a spanning tree on V vertices.
For every spanning tree on V vertices, the number of edges equals V - 1.
Narrator explains that if there were fewer edges, the graph would be disconnected.
If a spanning subgraph on V vertices has fewer than V - 1 edges, it is disconnected.
The subgraph is intended to include all V vertices.
For all subgraphs on V vertices with fewer than V - 1 edges.
Narrator explains that if there were more edges, it would form cycles, which is not allowed in a tree.
If a connected subgraph on V vertices has more than V - 1 edges, it contains a cycle and therefore is not a tree.
The subgraph includes all V vertices and is connected.
For all connected subgraphs on V vertices with more than V - 1 edges.
At 00:24-00:27 the narrator says, "This assumes the graph is stored in an adjacency list."
The code indexes `graph[start]` and `graph[v]` as iterable neighbor lists.
The displayed Prim's algorithm implementation assumes the input graph is stored in an adjacency list.
The function receives a parameter named `graph`.
`graph[node]` can be iterated to yield `(neighbor, weight)` pairs.
For the implementation shown in this clip.
The slide simplifies to `` under the heading `TIME COMPLEXITY`.
At 01:00-01:10 the narrator concludes the total time complexity is `Big O of E log V`.
For the heap-based implementation shown, the total time complexity is ``.
The graph has `V` vertices and `E` edges.
The priority queue is a binary heap.
Each edge is pushed about once and heap operations take logarithmic time.
Asymptotic worst-case bound for the algorithm as presented.
The slide simplifies to `` under the heading `SPACE COMPLEXITY`.
At 01:30-01:33 the narrator says, "Hence, the total space complexity is Big O of V plus E."
For the implementation shown, the total space complexity is ``.
The graph is stored as an adjacency list requiring ``.
The visited set uses ``.
The priority queue uses ``.
The MST edge list uses ``.
Asymptotic memory bound for the algorithm as presented.
Narrator walks through choosing A, then AB, then BD, then DC, then AF, and says all nodes are connected so the algorithm stops.
The graph highlights candidate edges in green and accepted edges in red as vertices turn yellow in sequence.
Choose vertex A as the starting vertex.
The narrator says, "Let's begin with node A."
Among edges incident to A, select AB with weight 2 and add it to the tree.
AB is the minimum-weight edge from the current tree {A}; the animation turns AB red and B yellow.
From the current tree {A, B}, consider edges crossing to outside vertices and select BD with weight 2.
The narrator says the minimum-cost highlighted edge is BD with weight 2; the animation adds BD in red and marks D yellow.
From the current tree {A, B, D}, select DC with weight 1 and add it.
DC is the minimum-weight admissible crossing edge; the animation colors DC red and marks C yellow.
From the current tree {A, B, D, C}, select AF with weight 3 and add it.
AF is the remaining minimum-weight edge needed to reach F; the animation colors AF red and marks F yellow.
Stop because all vertices are now included.
The narrator states that with this addition all nodes are connected and the algorithm stops.
The resulting minimum spanning tree consists of edges AB, BD, DC, and AF, with total weight .
Narrator gives the intuitive reason: fewer edges disconnect the graph, more edges create cycles.
This is an intuitive explanation rather than a formal proof.
A spanning tree on V vertices has exactly V - 1 edges.
Stated directly by the narrator and shown on screen.
If there were fewer than V - 1 edges, the graph would be disconnected.
Narrator's stated intuition about insufficient edges to connect all vertices.
If there were more than V - 1 edges, cycles would form.
Narrator's stated intuition that extra edges violate the tree condition.
The exact count V - 1 is forced by the simultaneous requirements of spanning all vertices and remaining acyclic.
The visual sequence is `` → `` → ``.
The narrator explains edge iteration, near-once pushes, logarithmic push cost, and the final simplification.
Iterating over all edges contributes linear time in the number of edges.
Stated directly by the narrator at 00:57-01:00 and shown on the slide.
Each edge can be pushed into the priority queue almost once, and each push costs logarithmic time.
Stated directly by the narrator at 01:00-01:07 and reflected in the second slide term.
The sum is simplified by keeping the dominant asymptotic term.
Shown visually on the slide and concluded verbally at 01:07-01:10.
The total running time of the presented heap-based Prim's algorithm is ``.
The visual sequence is `` → `` → `` → `` → ``.
The narrator assigns each term to the graph, visited set, priority queue, and MST edge list, then sums them.
The graph itself occupies `` space because it is stored as an adjacency list.
Stated by the narrator at 01:11-01:15 and shown as the first term on the slide.
The visited set occupies `` space since it stores at most all vertices.
Stated by the narrator at 01:16-01:20 and appended as the second term.
The priority queue occupies `` space because it may hold up to all edges during execution.
Stated by the narrator at 01:21-01:26 and appended as the third term.
The MST edge list occupies `` space.
Stated by the narrator at 01:26-01:30 and appended as the fourth term.
Adding the auxiliary bounds and simplifying gives the total memory requirement.
Shown visually on the slide and concluded verbally at 01:30-01:33.
The total space usage of the presented implementation is ``.
Weighted graph with vertices A, B, C, D, F and visible edge weights: AB=2, AF=3, AD=5, BD=2, BC=7, BF=4, CD=1.
Narrator says, "Now, let's find the minimum spanning tree for this example graph using Prim's algorithm."
Selected edges become red in the order AB, BD, DC, AF.
No vertex E is visible in the graph despite the five-letter label set A, B, C, D, F.
Find a minimum spanning tree of the displayed weighted graph using Prim's algorithm starting from vertex A.
Vertices shown: A, B, C, D, F.
Edge weights shown: AB=2, AF=3, AD=5, BD=2, BC=7, BF=4, CD=1.
Starting vertex: A.
Select a connected, acyclic subset of edges spanning all vertices with minimum total weight.
Begin with the single-vertex tree containing A.
Explicit start choice in the narration.
Add edge AB because it is the cheapest edge from A.
Minimum-weight incident edge from the current tree.
Add edge BD from the current tree {A,B}.
It is the minimum-cost admissible crossing edge mentioned by the narrator.
Add edge DC from the current tree {A,B,D}.
It is the minimum-weight edge selected next in the walkthrough.
Add edge AF to include the last vertex F.
Narrator selects AF as the next minimum-weight edge and then stops.
Sum the chosen edge weights to obtain the total tree weight.
Derived from the visible weights of the selected edges.
The minimum spanning tree is {AB, BD, DC, AF} with total weight 8.
The selected edges connect all displayed vertices A, B, C, D, F, contain edges for the visible vertex set, and form no cycle.
A static weighted undirected graph is shown with teal circular vertices labeled A, B, C, D, F and dark blue edges carrying numeric weights.
Vertices A, B, C, D, F
Edges with weights 1, 2, 2, 3, 4, 5, 7
The graph is introduced and remains unchanged while the definition and algorithm overview are spoken.
Vertex labels remain fixed.
Edge weights remain fixed.
The picture establishes the concrete instance on which Prim's algorithm will be demonstrated.
Vertex A turns yellow first; candidate edges from the current tree glow green; accepted edges turn red; newly included vertices turn yellow in sequence B, D, C, F.
Exact frame-by-frame timing of each color transition is approximate.
Current tree vertices highlighted yellow
Candidate crossing edges highlighted green
Accepted tree edges highlighted red
Start at A.
Highlight edges from A.
Select AB.
Expand candidate set from {A,B}.
Select BD.
Expand from {A,B,D}.
Select DC.
Expand from {A,B,D,C}.
Select AF.
All vertices become part of the tree.
Original graph topology and weights do not change.
Only color coding changes to indicate tree membership and candidates.
The animation visualizes Prim's greedy rule: maintain a connected tree and repeatedly attach the cheapest boundary edge.
Non-tree edges disappear or fade, leaving only the red tree edges AB, BD, DC, AF; text "V - 1 Edges" appears to the right.
Red spanning tree edges AB, BD, DC, AF
Yellow vertices A, B, C, D, F
Text "V - 1 Edges"
The display shifts from the full graph to the isolated spanning tree.
The formula text appears beside the tree.
The selected tree remains connected and acyclic.
The vertex set stays the same.
The visual emphasizes that the output is a spanning tree and that its size obeys the V - 1 edge rule.
Screen changes to Python code with syntax highlighting; boxes briefly emphasize `import heapq` and `def prims_algorithm(graph, start):`.
The code view is only partially traversed before the clip ends.
Python source code
Highlighted import line
Highlighted function definition
Graph visualization is replaced by code.
Attention boxes move from the import statement to the function signature.
The topic remains Prim's algorithm.
The code corresponds to the previously explained greedy procedure.
The video moves from conceptual demonstration to an algorithmic implementation using a heap-based priority queue.
A green rectangular outline highlights the four initialization lines inside the Python function.
The code block remains static while only the highlight box changes position.
Python code editor view
green highlight rectangle
variables `priority_queue`, `visited`, `mst_edges`, `total_cost`
The highlight encloses the initialization statements from 00:00 to about 00:17.
The narrator introduces each variable in the same order as the highlighted lines.
The underlying code text does not change during this interval.
The function signature `def prims_algorithm(graph, start):` stays visible above the highlighted block.
The visual emphasis maps the spoken explanation directly to the data structures that define the algorithm's state.
The green box moves down to `visited.add(start)` and then to the `for neighbor, weight in graph[start]:` / `heapq.heappush(...)` lines.
The highlighted code shows seeding from the start vertex and pushing its incident edges.
`visited.add(start)` line
`for neighbor, weight in graph[start]:` loop
`heapq.heappush(priority_queue, (weight, start, neighbor))` line
green highlight rectangle
The highlight shifts from the initialization block to the seeding statements.
The code view scrolls slightly downward around 00:26 to reveal more of the loop body.
The same Python implementation remains on screen.
The priority queue tuple format stays `(weight, source, destination)`.
The animation marks the transition from setup to the first greedy frontier construction.
The green box successively highlights `while priority_queue:`, `weight, u, v = heapq.heappop(priority_queue)`, `if v not in visited:`, the three update lines, and the inner neighbor-push block.
The visible code shows the full greedy loop and expansion step.
`while priority_queue:`
`heapq.heappop(priority_queue)`
`if v not in visited:`
`visited.add(v)`
`mst_edges.append((u, v))`
`total_cost += weight`
inner `for neighbor, weight in graph[v]:` block
green highlight rectangle
The highlight advances line group by line group in execution order.
The code view is scrolled so the lower portion of the function becomes visible.
The heap always supplies the minimum-weight candidate first.
The acceptance test is based on whether `v` is already in `visited`.
The moving box turns the static code into a temporal walkthrough of the algorithm's greedy cycle.
A beige slide titled `TIME COMPLEXITY` displays formulas that appear and simplify in sequence.
The expression changes from `` to `` and then to ``.
Title `TIME COMPLEXITY`
formula ``
formula ``
formula ``
First only `` is shown.
Then `+ ` is appended.
Finally the whole expression simplifies to ``.
The slide background and title remain fixed.
The variables `E` and `V` keep the same meanings across the sequence.
The visual simplification mirrors the verbal argument that heap operations dominate edge scanning.
The same slide adds the green title `SPACE COMPLEXITY` below the time result.
The space formula grows term by term and then collapses to ``.
Title `SPACE COMPLEXITY`
formula ``
formula ``
formula ``
formula ``
final formula ``
A new heading appears beneath the time-complexity result.
Terms are added one by one for graph storage, visited set, priority queue, and MST edge list.
The summed expression is replaced by the simplified total ``.
The earlier time result `` remains visible above.
`V` and `E` continue to denote vertex and edge counts.
The staged accumulation makes explicit which data structures contribute to memory usage before asymptotic simplification.
Narrator explicitly contrasts fewer edges causing disconnection and more edges causing cycles.
One might think a spanning tree can have fewer or more than V - 1 edges and still be valid.
Fewer than V - 1 edges cannot connect all V vertices, while more than V - 1 edges introduce cycles, so a spanning tree must have exactly V - 1 edges.
The narration repeatedly restricts selection to edges connected to the current tree and then chooses the minimum among those.
Only boundary edges from the yellow tree vertices are highlighted green before a red selection is made.
Prim's algorithm may be mistaken for simply picking the smallest edge anywhere in the graph at each step.
The video shows that Prim's algorithm chooses the minimum-weight edge crossing from the current tree to an outside vertex, not an arbitrary globally smallest unused edge.
At 00:36-00:47 the narrator says, "push all the edges connected to the current node onto the priority queue."
The visible code instead contains `if neighbor not in visited:` before `heapq.heappush(priority_queue, (weight, v, neighbor))`.
One may infer from the narration that every incident edge of the current node is pushed unconditionally into the priority queue.
The displayed implementation only pushes edges whose neighbor is not already in `visited`; the narration is broader than the code shown on screen.
The clip describes returning the edges and total cost of the minimum spanning tree but does not state a connectivity precondition.
The code itself contains no explicit check that all vertices were reached.
The code fragment alone may suggest it always produces a spanning tree for any input graph.
Analysis note: a minimum spanning tree exists for a connected weighted graph; if the graph is disconnected, the procedure as shown yields a minimum spanning forest rather than a single spanning tree. This condition is not mentioned in the clip.
Narrator introduces Prim's algorithm as the method for finding the minimum spanning tree of the example graph.
Prim's algorithm is presented as a method for constructing a minimum spanning tree.
Narrator says a priority queue stores edges so the minimum-weight edge can be retrieved quickly.
The priority queue is the data structure used to implement the greedy edge-selection step in Prim's algorithm.
Narrator states the V - 1 edge property specifically for any minimum spanning tree.
The edge-count formula is a structural property contained in the definition of a spanning tree and hence of a minimum spanning tree.
The code defines `prims_algorithm` and uses `heapq` with a visited set and candidate-edge heap.
The Python code is an implementation of the previously explained Prim's algorithm procedure.
The worked graph execution follows exactly the greedy rule described earlier.
The example demonstrates the abstract method on a concrete weighted graph.
The initialization block defines the containers used immediately afterward in `visited.add(start)` and the first `heapq.heappush` loop.
The seeding step cannot run until the priority queue, visited set, edge list, and cost accumulator have been created.
The first pushed edges populate `priority_queue`, which is then consumed by `while priority_queue:` and `heapq.heappop(priority_queue)`.
The main greedy loop operates on the frontier created by the initial seeding step.
The `if v not in visited:` test gates execution of `visited.add(v)`, `mst_edges.append((u, v))`, `total_cost += weight`, and the neighbor-expansion loop.
An edge is accepted and the frontier expanded only after the minimum candidate is popped and its destination passes the visited test.
Accepted edges and accumulated cost are stored in `mst_edges` and `total_cost`, which are exactly the values returned by `return mst_edges, total_cost`.
The final output depends on the records built during each acceptance step.
The time-complexity explanation refers to iterating over edges and pushing them into the priority queue, which are the operations in the loop body.
The slide derives `` from those same heap-based operations.
The time bound is obtained by analyzing the repeated pop-and-push behavior of the main loop.
The space explanation names the graph, visited set, priority queue, and MST edge list.
These are precisely the structures initialized in the code and summed on the slide.
The space bound is derived by adding the memory requirements of the data structures introduced at initialization.
The same slide presents `TIME COMPLEXITY` above `SPACE COMPLEXITY` with different final expressions.
The clip distinguishes runtime cost, dominated by heap operations, from memory cost, dominated by storing the graph and auxiliary structures.
Opening narration defines the concept directly.
Narrator explains the greedy construction and then demonstrates it on an example.
Narrator gives the reason using disconnection and cycles.
Narrator says the priority queue allows quick retrieval of the minimum-weight edge.
Visible Python code introduces the implementation structure.
The full function body is not shown in this clip.
Selected red edges are AB, BD, DC, AF with visible weights 2, 2, 1, 3.
The initialization lines are visible and narrated.
The narrator explains adding the starting node and pushing its neighboring edges.
The corresponding code is highlighted on screen.
The code shows `if v not in visited:` immediately after popping from the heap.
The narrator says the algorithm checks whether the node is already in the visited set.
The highlighted block updates `visited`, `mst_edges`, `total_cost`, and pushes new edges.
The narrator explicitly states the adjacency-list assumption.
The slide shows the simplification to ``.
The narrator explains edge iteration and logarithmic heap pushes.
Covered · Definition of minimum spanning tree over the initial weighted graph.
Covered · High-level description of Prim's algorithm before the worked run.
Covered · Step-by-step animated execution of Prim's algorithm on the example graph.
Covered · Final tree display and explanation of the V - 1 edge property.
Covered · Introduction of the Python implementation using heapq; only the beginning of the code is visible.
Covered · Code initialization block is shown and explained variable by variable.
Covered · Start vertex is marked visited and its incident edges are pushed; adjacency-list assumption is stated.
Covered · While-loop condition, minimum-edge pop, and visited test are shown and narrated.
Covered · Acceptance updates and neighbor expansion are shown; slight narration-code mismatch is recorded as a misconception.
Covered · Function return statement is highlighted and explained.
Covered · Transition from code view to complexity slide; no additional mathematical content beyond scene change.
Covered · Time-complexity slide builds from `` to `` with spoken justification.
Covered · Space-complexity slide accumulates component bounds and simplifies to ``.
Reviewed English material v1: card/concept_card "Minimum spanning tree" starting at 0:00 — A minimum spanning tree is a spanning subgraph of a weighted graph that includes every vertex, remains connected, contains no cycles, and has the smallest possible sum of edge weights among all such subgraphs.