Adjacency matrix graphs use a 2D matrix to represent graph connections. Cell (i, j) in the matrix indicates whether there’s an edge from vertex i to vertex j. UCX DSA provides both weighted and unweighted adjacency matrix implementations.
Adjacency matrix graphs offer O(1) edge lookup time but require O(V²) space, making them ideal for dense graphs or applications requiring frequent edge existence checks.
The matrix stores True for existing edges and None for non-edges:
g = AdjacencyMatrixGraph(vertices=['A', 'B', 'C'])g.add_edge('A', 'B')g.add_edge('B', 'C')# Internal matrix (directed=False):# A B C# A None True None# B True None True# C None True None
g = AdjacencyMatrixGraph(vertices=['A', 'B', 'C'])print(g.has_vertex('A')) # Trueprint(g.has_vertex('D')) # False# Can also use 'in' operatorif 'B' in g: print("Vertex B exists")
Parameters:
label (str): The vertex label to check
Returns:True if vertex exists, False otherwiseTime Complexity: O(1)
g = AdjacencyMatrixGraph(directed=False)# Vertices are created automatically if they don't existg.add_edge('A', 'B')g.add_edge('B', 'C')g.add_edge('C', 'D')print(g.order()) # 4 vertices createdprint(g.size()) # 3 edges
Parameters:
start_label (str): Starting vertex label
end_label (str): Ending vertex label
directed (bool, optional): Override graph’s directionality for this edge. Defaults to graph’s setting
Behavior:
For undirected graphs: Creates edge in both directions
For directed graphs: Creates edge only from start to end
Automatically creates vertices if they don’t exist
Returns:True if edge exists, False otherwiseRaises:KeyError if either vertex doesn’t existTime Complexity: O(1) - this is the main advantage of adjacency matrices!
Display the adjacency matrix in a readable format.
g = AdjacencyMatrixGraph(directed=False, vertices=['A', 'B', 'C'])g.add_edge('A', 'B')g.add_edge('B', 'C')g.print_graph()# Output:# | A B C # ----------------# A | T # B | T T # C | T
g = AdjacencyMatrixWeightedGraph(directed=False, vertices=['A', 'B', 'C'])g.add_edge('A', 'B', 10)g.add_edge('B', 'C', 20)g.add_edge('A', 'C', 5)g.print_graph()# Output:# | A B C # ----------------# A | 10 5 # B | 10 20 # C | 5 20
from dsa.graph import AdjacencyMatrixWeightedGraph# Create a graph of cities with distancescities = AdjacencyMatrixWeightedGraph( directed=False, vertices=['NYC', 'Boston', 'DC', 'Philadelphia'])# Add roads with distances in milescities.add_edge('NYC', 'Boston', 215)cities.add_edge('NYC', 'Philadelphia', 95)cities.add_edge('NYC', 'DC', 225)cities.add_edge('Philadelphia', 'DC', 140)cities.add_edge('Boston', 'Philadelphia', 300)# Query distancesprint(f"NYC to Boston: {cities.get_weight('NYC', 'Boston')} miles")print(f"Cities from NYC: {cities['NYC']}")# Show the matrixcities.print_graph()
from dsa.graph import AdjacencyMatrixGraph# Create a directed graph for tournament resultstournament = AdjacencyMatrixGraph( directed=True, vertices=['Team A', 'Team B', 'Team C', 'Team D'])# Add edges for "team X beat team Y"tournament.add_edge('Team A', 'Team B') # A beat Btournament.add_edge('Team A', 'Team C') # A beat Ctournament.add_edge('Team B', 'Team D') # B beat Dtournament.add_edge('Team C', 'Team D') # C beat Dtournament.add_edge('Team D', 'Team A') # D beat A# Find who each team beatfor team in tournament.vertices(): beaten = tournament[team] print(f"{team} beat: {beaten}")# Find who beat Team Afor team in tournament.vertices(): if tournament.has_edge(team, 'Team A'): print(f"{team} beat Team A")