A Graph is a non-linear data structure consisting of nodes (also called vertices) and edges. An edge connects a pair of nodes, indicating a relationship between them. Graphs are used to model networks and relationships in a huge variety of applications, from social networks to mapping applications.
(u, v) goes from vertex u to vertex v. (Think of a one-way street).(u, v) is the same as (v, u). (Think of a two-way street).!Graph Diagram
There are two common ways to represent a graph in code:
An adjacency matrix is a 2D array (a list of lists) of size V x V where V is the number of vertices. A slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j.
An adjacency list represents a graph as an array of lists. The size of the array is equal to the number of vertices. An entry adj[i] is a list of vertices adjacent to the i-th vertex.
In Python, it's common to use a dictionary for an adjacency list, where each key is a vertex and its value is a list of its neighbors. This is the most common and generally most efficient method for most problems.
Let's model a simple social network using an adjacency list.
class Graph:
def __init__(self):
self.adj_list = {}
def add_vertex(self, vertex):
if vertex not in self.adj_list:
self.adj_list[vertex] = []
# For an undirected graph, add edges in both directions
def add_edge(self, v1, v2):
if v1 in self.adj_list and v2 in self.adj_list:
self.adj_list[v1].append(v2)
self.adj_list[v2].append(v1)
def print_graph(self):
for vertex, edges in self.adj_list.items():
print(vertex, ":", edges)
--- Usage ---
g = Graph()
g.add_vertex("Alice")
g.add_vertex("Bob")
g.add_vertex("Charlie")
g.add_edge("Alice", "Bob")
g.add_edge("Bob", "Charlie")
g.print_graph()
The output shows who is "friends" with whom:
Alice : ['Bob']
Bob : ['Alice', 'Charlie']
Charlie : ['Bob']
Graph Traversal: Just like trees, graphs have traversal algorithms. The two most famous are Breadth-First Search (BFS), which explores neighbor nodes first, and Depth-First Search (DFS), which explores as far as possible along each branch before backtracking. These are essential for solving many graph problems.
In a social network graph, what would the vertices and edges typically represent?