Created
March 4, 2025 06:44
-
-
Save siavashk/c6f20b191018660231a74c50f2fddb46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
def iterative_minimum_spanning_tree(adj, start_node=0): | |
mst = [] | |
visited = set() | |
min_heap = [(0, start_node, -1)] # (weight, current_node, parent_node) | |
while min_heap: | |
weight, node, parent = heapq.heappop(min_heap) | |
if node in visited: | |
continue | |
visited.add(node) | |
if parent != -1: | |
mst.append((parent, node, weight)) | |
for neighbor, edge_weight in adj[node]: | |
if neighbor not in visited: | |
heapq.heappush(min_heap, (edge_weight, neighbor, node)) | |
return mst |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment