Python Graphs


Graph is a non-linear data structure that represents relationships between pairs of elements (called nodes or vertices) using edges.

Graphs can be:

  • Directed or Undirected

  • Weighted or Unweighted


🔹 Basic Graph Terms

Term Meaning
Vertex A node in the graph
Edge A connection between two vertices
Adjacent Two vertices connected by an edge
Path A sequence of vertices connected by edges
Degree Number of edges connected to a node

🔹 Representing a Graph in Python

1. Using Adjacency List (Dictionary)
graph = {
    'A': ['B', 'C'],
    'B': ['D'],
    'C': ['E'],
    'D': ['F'],
    'E': [],
    'F': []
}

2. Using Adjacency Matrix
vertices = ['A', 'B', 'C']
matrix = [
    [0, 1, 1],
    [0, 0, 0],
    [0, 0, 0]
]

🔹 Depth-First Search (DFS)

def dfs(graph, node, visited):
    if node not in visited:
        print(node)
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)

visited = set()
dfs(graph, 'A', visited)

✅ Output:

A
B
D
F
C
E

🔹 Breadth-First Search (BFS)

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])

    while queue:
        vertex = queue.popleft()
        if vertex not in visited:
            print(vertex)
            visited.add(vertex)
            queue.extend(graph[vertex])

bfs(graph, 'A')

✅ Output:

A
B
C
D
E
F

🔹 Directed vs Undirected Graph

  • Directed: Edges have direction → (A → B)

  • Undirected: Edges go both ways (A — B)


🔹 Use Cases of Graphs

  • Social networks (users connected to users)

  • Maps and navigation (cities connected by roads)

  • Web crawlers (pages connected via links)

  • Network routing

  • AI pathfinding (games, robotics)


Practice Questions

Q1. Write a Python program to create an undirected graph with 5 nodes using an adjacency list.

Q2. Write a Python program to implement a function to add new vertices to the graph.

Q3. Write a Python program to traverse the graph using Depth-First Search (DFS).

Q4. Write a Python program to traverse the graph using Breadth-First Search (BFS).

Q5. Write a Python program to count the number of connections (edges) for a given node.

Q6. Write a Python program to check if two nodes are connected directly.

Q7. Write a Python program to list all paths between two nodes using recursion or DFS.

Q8. Write a Python program to convert an adjacency list into an adjacency matrix.

Q9. Write a Python program to mark and print all visited nodes during a DFS traversal.

Q10. Write a Python program to create a weighted undirected graph using a dictionary of dictionaries or a tuple-based structure.


Go Back Top