2026-04-20
Course Evaluation Menu/link on your Canvassingle-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 includedINFINITY as the string value "-", which prints nicely.O(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:
from graph import LinkedDirectedGraph
g = LinkedDirectedGraph()
# Insert vertices
g.addVertex("A")
g.addVertex("B")
g.addVertex("C")
g.addVertex("D")
g.addVertex("E")
# Insert weighted edges
g.addEdge("A", "B", 3)
g.addEdge("A", "C", 2)
g.addEdge("B", "D", 1)
g.addEdge("C", "D", 1)
g.addEdge("D", "E", 2)
print(g)5 Vertices: A C B E D5 Edges: A>B:3 A>C:2 B>D:1 C>D:1 D>E:2The next code segment displays the neighboring vertices and the incident edges of the vertex labeled A in this example graph:
Neighboring vertices of A
print("Neighboring vertices of A:")
for vertex in g.neighboringVertices("A"):
print(vertex)
# Output:
Neighboring vertices of A:
B
CAAbstractCollectionadd method adds a vertex with the given label to a graphlen function returns the number of the graph’s verticesfor loop visits the graph’s verticesin operator returns True if the graph contains a given vertex== operator compares vertices in the two graph operands+ operator creates a new graph that contains the vertices of its two operandsLinkedDirectedGraphLinkedVertexLinkedEdgeLinkedDirectedGraph(1/2)The LinkedDirectedGraph class typically provides the following methods:
| Method | What It Does |
|---|---|
| Graph Creation | |
g = LinkedDirectedGraph(sourceCollection=None) |
Creates a new directed graph using an adjacency list. Optionally adds vertices from a collection of labels. |
| Clearing, Size, and String Representation | |
g.clear() |
Removes all vertices from the graph. |
g.clearEdgeMarks() |
Clears all edge marks. |
g.clearVertexMarks() |
Clears all vertex marks. |
g.isEmpty() |
Returns True if the graph contains no vertices. |
g.sizeEdges() |
Returns the number of edges in the graph. |
g.sizeVertices() |
Returns the number of vertices in the graph. |
g.__str__() |
Returns a string representation of the graph. |
| Vertex-Related Methods | |
g.containsVertex(label) |
Returns True if the graph contains a vertex with the specified label. |
g.addVertex(label) |
Adds a vertex with the specified label. |
g.getVertex(label) |
Returns the vertex with the specified label, or None if not found. |
g.removeVertex(label) |
Removes and returns the vertex with the specified label, or None if not found. |
LinkedDirectedGraph (2/2)| Method | What It Does |
|---|---|
| Edge-Related Methods | |
g.containsEdge(fromLabel, toLabel) |
Returns True if an edge exists from fromLabel to toLabel. |
g.addEdge(fromLabel, toLabel, weight=None) |
Adds an edge with the specified weight between the given vertices. |
g.getEdge(fromLabel, toLabel) |
Returns the edge between the specified vertices, or None if not found. |
g.removeEdge(fromLabel, toLabel) |
Removes the edge and returns True if successful, else False. |
| Iterators | |
g.edges() |
Returns an iterator over the edges in the graph. |
g.getVertices() |
Returns an iterator over the vertices in the graph. |
g.incidentEdges(label) |
Returns an iterator over the incident edges of the vertex with the given label. |
g.neighboringVertices(label) |
Returns an iterator over the neighboring vertices of the given vertex. |
LinkedDirectedGraph ADTThe implementation of LinkedDirectedGraph maintains a dictionary whose keys are labels and whose values are the corresponding vertices
Code for the class header and constructor:
class LinkedDirectedGraph(AbstractCollection):
def __init__(self, sourceCollection = None):
self.edgeCount = 0
self.vertices = dict() # Dictionary of vertices {}
AbstractCollection.__init__(self, sourceCollection)LinkedDirectedGraph class is inheriting AbstractCollection classLinkedDirectedGraphdef addEdge(self, fromLabel, toLabel, weight):
"""Connects the vertices with an edge with the given weight."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
fromVertex.addEdgeTo(toVertex, weight)
self.edgeCount += 1
def getEdge(self, fromLabel, toLabel):
"""Returns the edge connecting the two vertices, or None if
no edge exists."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
return fromVertex.getEdgeTo(toVertex)
def removeEdge(self, fromLabel, toLabel):
"""Returns True if the edge was removed, or False otherwise."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
edgeRemovedFlg = fromVertex.removeEdgeTo(toVertex)
if edgeRemovedFlg:
self.edgeCount -= 1
return edgeRemovedFlgLinkedVertex| Method | What It Does |
|---|---|
LinkedVertex(label) |
Creates a vertex with the specified label. The vertex is initially unmarked. |
clearMark() |
Unmarks the vertex. |
setMark() |
Marks the vertex. |
isMarked() |
Returns True if the vertex is marked, or False otherwise. |
getLabel() |
Returns the label of the vertex. |
setLabel(label, g) |
Changes the label of the vertex in graph g to label. |
addEdgeTo(toVertex, weight) |
Adds an edge with the given weight from this vertex to toVertex. |
getEdgeTo(toVertex) |
Returns the edge from this vertex to toVertex, or None if the edge does not exist. |
incidentEdges() |
Returns an iterator over the incident edges of the vertex. |
neighboringVertices() |
Returns an iterator over the neighboring vertices of the vertex. |
__str__() |
Returns a string representation of the vertex. |
__eq__(anyObject) |
Returns True if anyObject is a vertex and the two labels are the same. |
LinkedEdge| Method | What It Does |
|---|---|
LinkedEdge(fromVertex, toVertex, weight=None) |
Creates an edge with the specified vertices and weight. It is initially unmarked. |
clearMark() |
Unmarks the edge. |
setMark() |
Marks the edge. |
isMarked() |
Returns True if the edge is marked, or False otherwise. |
getWeight() |
Returns the weight of the edge. |
setWeight(weight) |
Sets the edge’s weight to the specified weight. |
getOtherVertex(vertex) |
Returns the edge’s other vertex. |
getToVertex() |
Returns the edge’s destination vertex. |
__str__() |
Returns the string representation of the edge. |
__eq__(anyObject) |
Returns True if anyObject is an edge and the two edges are connected to the same vertices and have the same weight. |
_eq_ method:class LinkedEdge(object):
def __init__(self, fromVertex, toVertex, weight = None):
self.vertex1 = fromVertex
self.vertex2 = toVertex
self.weight = weight
self.mark = False
def __eq__(self, other):
"""Two edges are equal if they connect
the same vertices."""
if self is other: return True
if type(self) != type(other): return False
return self.vertex1 == other.vertex1 and \
self.vertex2 == other.vertex2 and \
self.weight == other.weightTasks
Complete the classes in the case study and test the operations to input a graph and display it.
Complete the function spanTree in the case study and test it thoroughly.
Complete the function shortestPaths in the case study and test it thoroughly
show-&-tell by demonstrating their solution