Dijkstradalh
Dijkstradalh
Prim’s Algorithm:
Description:
The algorithm starts with an empty spanning tree. The idea is to maintain two sets of vertices. The first set
contains the vertices already included in the MST, and the other set contains the vertices not yet included. At
every step, it considers all the edges that connect the two sets and picks the minimum weight edge from these
edges.
After picking the edge, it moves the other endpoint of the edge to the set containing MST. This algorithm
always starts with a single node and moves through several adjacent nodes, in order to explore all of the
connected edges along the way.
Source Code:
graph = {
0: [(1, 2), (3, 6)],
1: [(0, 2), (2, 3), (3, 8), (4, 5)],
2: [(1, 3), (4, 7)],
3: [(0, 6), (1, 8)],
4: [(1, 5), (2, 7)]
}
V=5
print("MST (Prim's):", prim(graph, V))
Output:
MST (Prim's): [(0, 1, 2), (1, 2, 3), (1, 4, 5), (0, 3, 6)]
Kruskal’s Algorithm:
Description:
In Kruskal’s algorithm, sort all edges of the given graph in increasing order. Then it keeps on adding new
edges and nodes in the MST if the newly added edge does not form a cycle. It picks the minimum weighted
edge at first and the maximum weighted edge at last. Thus we can say that it makes a locally optimal choice in
each step in order to find the optimal solution. Hence this is a Greedy Algorithm.
Source Code:
def find(u):
if parent[u] != u:
parent[u] = find(parent[u])
return parent[u]
mst = []
min_cost = 0
edges.sort(key=lambda x: x[2]) # Sort by weight
for u, v, weight in edges:
if find(u) != find(v):
mst.append((u, v, weight))
union(u, v)
min_cost += weight
# Example usage
edges = [
(0, 1, 2),
(0, 3, 6),
(1, 2, 3),
(1, 3, 8),
(1, 4, 5),
(2, 4, 7)
]
V=5
mst = kruskals_algorithm(edges, V)
print("MST (Kruskal's):", mst)
print(" Minimum Cost: ”,min_cost)
Output:
MST (Kruskal's): [(0, 1, 2), (1, 2, 3), (1, 4, 5), (0, 3, 6)]
Experiment 10
Description:
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we
generate an SPT (shortest path tree) with a given source as the root. We maintain two sets, one set contains
vertices included in the shortest path tree, other set includes vertices not yet included in the shortest path tree.
At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a
minimum distance from the source.
Source Code:
def dijkstra(graph, V, source):
dist = [float('inf')] * V
dist[source] = 0
visited = [False] * V
for _ in range(V):
u = min((v for v in range(V) if not visited[v]), key=lambda v: dist[v], default=None)
if u is None or dist[u] == float('inf'):
break
visited[u] = True
for v, weight in graph[u]:
if not visited[v] and dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
return dist
graph = {
0: [(1, 2), (2, 4)],
1: [(2, 1), (3, 7)],
2: [(3, 3)],
3: []
}
V=4
source = 0
print("Shortest distances (Dijkstra's):", dijkstra(graph, V, source))
Output: