Adjacency List in a Graph
Understanding Graph Representation in Python with Adjacency Lists
In this post, we'll explore how to represent a graph using adjacency lists in Python, utilizing the defaultdict
from the collections
module. Graphs are a powerful data structure that allows us to model relationships between nodes (or vertices) with connections (or edges). This representation is particularly useful when you need to store and visualize relationships, like social networks, maps, or web page links.
Let's dive into the code and break it down step by step.
Code Overview
Here’s a Python implementation that reads a graph from user input and outputs the adjacency list representation of the graph.
Python Code:
Input
The program starts by reading the number of vertices (v
) and edges (e
). Then, for each edge, it adds a bidirectional connection between two nodes.
For example, the input:
This represents a graph with 7 vertices and 9 edges, where each line after the vertex/edge count defines an edge between two vertices (e.g., A B
means there’s an edge between vertex A and vertex B).
Output
The program then outputs the adjacency list representation of the graph. For each node, it shows the list of nodes it is directly connected to. Based on the input above, the output will look like this:
How the Code Works
Using defaultdict:
We usedefaultdict(list)
to initialize our graph. This ensures that if we try to access a key that doesn't yet exist, it automatically creates an empty list for that key. This is perfect for building an adjacency list where each node will map to a list of its neighboring nodes.Adding Edges:
For each edge, we add both connections. Since it’s an undirected graph, if there is an edge betweenA
andB
, then we need to appendB
to the list of neighbors forA
, andA
to the list of neighbors forB
.Printing the Graph:
Once all edges are added, we loop through each node in the graph and print its neighbors in the formatnode -> [neighbor1, neighbor2, ...]
. This gives us a visual representation of the graph's structure.
Understanding the Output
Let’s break down the output:
F -> ['A', 'C', 'G']
Node F is connected to nodes A, C, and G.C -> ['A', 'E', 'F', 'D']
Node C has four neighbors: A, E, F, and D.G -> ['D', 'F']
Node G is connected to nodes D and F.
This adjacency list format is a convenient way to represent a graph because it shows, for each node, the nodes it's directly connected to. This format can easily be used in graph algorithms like depth-first search (DFS), breadth-first search (BFS), or shortest-path algorithms.
Comments
Post a Comment