Skip to main content

Overview

The AdjacencyMatrixWeightedGraph class represents a weighted graph using an adjacency matrix. It extends AdjacencyMatrixGraph and stores edge weights as numeric values in a 2D matrix. Supports both directed and undirected graphs.

Constructor

AdjacencyMatrixWeightedGraph(directed=False, vertices=None)
directed
bool
default:"False"
Whether the graph is directed
vertices
list[str]
default:"None"
List of vertex labels to initialize the graph with
Raises: ValueError if duplicate vertex labels are provided
from dsa.graph import AdjacencyMatrixWeightedGraph

# Create empty weighted graph
g = AdjacencyMatrixWeightedGraph()

# Create directed weighted graph
g = AdjacencyMatrixWeightedGraph(directed=True)

# Create with initial vertices
g = AdjacencyMatrixWeightedGraph(vertices=['A', 'B', 'C'])

Attributes

is_directed
bool
Whether the graph is directed
is_weighted
bool
Whether the graph is weighted (always True)
labels
list[str]
List of all vertex labels in the graph

Methods

add_edge

Add a weighted edge between two vertices.
add_edge(start_label: str, end_label: str, weight, directed=None)
start_label
str
required
Starting vertex label
end_label
str
required
Ending vertex label
weight
numeric
required
The weight of the edge
directed
bool
default:"None"
Override the graph’s default directed behavior. If None, uses self.is_directed
g = AdjacencyMatrixWeightedGraph()

# Add weighted edges
g.add_edge('A', 'B', 5)
g.add_edge('B', 'C', 10)
g.add_edge('A', 'C', 15)

# Add directed edge in undirected graph
g.add_edge('C', 'D', 7, directed=True)

# Vertices are auto-created if they don't exist
g.add_edge('E', 'F', 20)

get_weight

Get the weight of an edge between two vertices.
get_weight(start_label: str, end_label: str) -> numeric
start_label
str
required
Starting vertex label
end_label
str
required
Ending vertex label
return
numeric
The weight of the edge from start to end
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
weight = g.get_weight('A', 'B')
print(weight)  # 5

edges

Get a list of all weighted edges in the graph.
edges() -> list
return
list[tuple]
List of edges, each represented as a tuple (start, end, weight)
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
g.add_edge('B', 'C', 10)
print(g.edges())  # [('A', 'B', 5), ('B', 'A', 5), ('B', 'C', 10), ('C', 'B', 10)]

undirected_edges

Get a list of weighted edges without duplicates for undirected graphs.
undirected_edges() -> list
return
list[tuple]
List of unique weighted edges, each represented as a tuple (start, end, weight)
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
g.add_edge('B', 'C', 10)
print(g.undirected_edges())  # [('A', 'B', 5), ('B', 'C', 10)]

adjacent_items

Get a list of adjacent vertices with their edge weights.
adjacent_items(vertex: str) -> list
vertex
str
required
The vertex label
return
list[tuple]
List of tuples (neighbor_label, weight)
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
g.add_edge('A', 'C', 10)
print(g.adjacent_items('A'))  # [('B', 5), ('C', 10)]
Print a visual representation of the weighted adjacency matrix.
print_graph()
g = AdjacencyMatrixWeightedGraph(vertices=['A', 'B', 'C'])
g.add_edge('A', 'B', 5)
g.add_edge('B', 'C', 10)
g.print_graph()
# Output:
#    |  A   B   C  
# ----------------
#  A |      5      
#  B |  5      10  
#  C |     10      

to_dict

Convert the graph to a dictionary representation.
to_dict() -> dict
return
dict
Dictionary where keys are vertices and values are dictionaries mapping neighbors to weights
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
g.add_edge('B', 'C', 10)
print(g.to_dict())
# {'A': {'B': 5}, 'B': {'A': 5, 'C': 10}, 'C': {'B': 10}}

Class Methods

from_dict

Create a weighted graph from a dictionary representation.
@classmethod
from_dict(data: dict, directed: bool = False) -> AdjacencyMatrixWeightedGraph
data
dict
required
Dictionary where keys are vertices and values are dictionaries mapping neighbors to weights
directed
bool
default:"False"
Whether the graph is directed
return
AdjacencyMatrixWeightedGraph
A new weighted graph instance
data = {
    'A': {'B': 5, 'C': 10},
    'B': {'A': 5, 'D': 15},
    'C': {'A': 10},
    'D': {'B': 15}
}
g = AdjacencyMatrixWeightedGraph.from_dict(data)

Special Methods

__getitem__

Get adjacent vertices and weights using bracket notation.
g = AdjacencyMatrixWeightedGraph()
g.add_edge('A', 'B', 5)
g.add_edge('A', 'C', 10)
print(g['A'])  # {'B': 5, 'C': 10}

Inherited Methods

The following methods are inherited from AdjacencyMatrixGraph:
  • add_vertex(label) - Add a vertex
  • delete_vertex(label) - Delete a vertex
  • delete_edge(start, end, directed=None) - Delete an edge
  • has_vertex(label) - Check if vertex exists
  • has_edge(start, end) - Check if edge exists
  • vertices() - Get all vertices
  • adjacents(vertex) - Get adjacent vertices (without weights)
  • order() - Get number of vertices
  • size() - Get number of edges
  • __len__() - Get number of vertices
  • __contains__(label) - Check vertex membership

Complete Examples

from dsa.graph import AdjacencyMatrixWeightedGraph

# Create road network with distances
g = AdjacencyMatrixWeightedGraph()

# Add roads with distances in km
g.add_edge('Seattle', 'Portland', 280)
g.add_edge('Portland', 'Eugene', 175)
g.add_edge('Seattle', 'Spokane', 450)
g.add_edge('Spokane', 'Boise', 630)
g.add_edge('Eugene', 'Boise', 665)

print(f"Cities: {g.vertices()}")
print(f"Roads: {g.undirected_edges()}")

# Get distance between cities
distance = g.get_weight('Seattle', 'Portland')
print(f"Seattle to Portland: {distance} km")

# Get all distances from Seattle
seattle_routes = g.adjacent_items('Seattle')
print(f"Routes from Seattle: {seattle_routes}")

Performance

  • Space Complexity: O(V²) where V is the number of vertices
  • Add Vertex: O(V²) - requires resizing matrix
  • Delete Vertex: O(V²) - requires resizing matrix
  • Add Edge: O(1)
  • Delete Edge: O(1)
  • Has Edge: O(1)
  • Get Weight: O(1)
  • Get Adjacents: O(V)
  • Get All Edges: O(V²)

Notes

  • Best for dense graphs where most vertices are connected
  • Provides O(1) edge weight lookup
  • Weights can be any numeric type (int, float, etc.)
  • Self-loops are prevented (diagonal is set to None)
  • For undirected graphs, edge weights are stored symmetrically
  • Vertex labels must be strings
  • Useful for shortest path algorithms (Dijkstra, Floyd-Warshall)
  • Ideal for minimum spanning tree algorithms (Prim, Kruskal)

Build docs developers (and LLMs) love