2025-11-19
Here is a weighted graph with six vertices. Each edge has a weight, shown by a number alongside the edge.

How can you pick a subgraph that minimizes the cost of connecting vertices into a network?
The MST for the graph above

The minimum spanning tree consists of the edges AB, AC, CD, DE, and EF, for a total edge weight of 28
The order in which the edges are specified is unimportant.
single-source shortest path problem asks for a solution that contains the shortest paths from a given vertex to all other vertices:
all-pairs shortest path problem, asks for the set of all the shortest paths in a graph:
results as 2D array.included, of N Booleans
for each vertex in the graph
Store vertex in the current row of the results grid
If vertex = source vertex
Set the row’s distance cell to 0
Set the row’s parent cell to undefined
Set included[row] to True
Else if there is an edge from source vertex to vertex
Set the row’s distance cell to the edge’s weight
Set the row’s parent cell to source vertex
Set included[row] to False
Else
Set the row’s distance cell to infinity
Set the row’s parent cell to undefined
Set included[row] to False
Go to the next row in the results gridA graph and the initial state of the data structures used to compute the shortest paths from a given vertex

Do
Find the vertex F that is not yet included and has the minimal distance in the results grid
Mark F as included
For each other vertex T not included
If there is an edge from F to T
Set new distance to F’s distance + edge’s weight
If new distance < T’s distance in the results grid
Set T’s distance to new distance
Set T’s parent in the results grid to F
While at least one vertex is not includedO(n)For each vertex v in a graph, the algorithm finds the shortest path from vertex v to any other vertex w that is reachable from v
Consider the weighted graph in this Figure

Using the figure above, you will build an initial distance matrix whose cells contain the weights on the edges that connect each vertex with its neighbors

Using the figure above, here is the modified distance matrix:

Pseudocode: