0% found this document useful (0 votes)
3 views

Algorithm Prim's Algorithm

Uploaded by

ameykhodke430
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Algorithm Prim's Algorithm

Uploaded by

ameykhodke430
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Algorithm: Prim's Algorithm

Input: cost[V][V] // Adjacency matrix of the graph


vertices // Number of vertices in the graph

1. Initialize:
visited[] = [false, false, ..., false] // All vertices are unvisited
visited[0] = true // Start from vertex 0
mincost = 0 // Total cost of MST
edgecount = 0 // Count of edges in MST

2. Repeat until edgecount < vertices - 1:


a. Set min = INF, x = 0, y = 0
b. For each vertex i that is visited:
For each vertex j that is not visited:
If cost[i][j] < min:
min = cost[i][j]
x = i
y = j
c. Mark vertex y as visited
d. Print edge (x, y) with its cost
e. Add cost[x][y] to mincost
f. Increment edgecount by 1

3. Print "The cost of Minimum Spanning Tree is: mincost"

Algorithm: Dijkstra's Shortest Path

Input: graph[V][V] // Adjacency matrix of the graph


src // Source vertex

1. Initialize:
dist[] = {∞, ∞, ..., ∞} // Distance to all vertices is initially infinity
dist[src] = 0 // Distance to the source is 0
sptSet[] = {false, false, ..., false} // No vertex is included in SPT

2. Repeat for count = 0 to V-1:


a. Find u = vertex with minimum dist[] value that is not yet in sptSet[].
(Use function minDistance(dist[], sptSet[]))
b. Mark u as included in sptSet[]: sptSet[u] = true

c. For each vertex v in the graph:


If graph[u][v] > 0 AND v is not in sptSet[] AND
dist[v] > dist[u] + graph[u][v]:
Update dist[v] = dist[u] + graph[u][v]

3. Print dist[] as the shortest distances from the source vertex.

Output: Shortest distance from the source vertex to all other vertices.

Kruskal
1. Initialize the graph with vertices and edges.
2. Sort the edges in non-decreasing order of their weights.
3. Initialize the `parent` array for Union-Find.
4. Create an empty list to store the edges of the MST.
5. For each edge (source, destination, weight) in sorted edges:
a. Find the root of the source vertex.
b. Find the root of the destination vertex.
c. If the roots are different:
i. Add the edge to the MST.
ii. Union the two sets by updating the parent array.
6. Output the edges of the MST.

You might also like