Photo AI

Last Updated Sep 27, 2025

Graphs Simplified Revision Notes

Revision notes with simplified explanations to understand Graphs quickly and effectively.

user avatar
user avatar
user avatar
user avatar
user avatar

381+ students studying

Graphs

Overview

A graph is a data structure used to model relationships between objects. It consists of nodes (also called vertices) and edges (connections between nodes). Graphs are widely used in various fields, such as networking (e.g., the Internet), social networks, and pathfinding algorithms in maps.

Graphs can be:

  • Directed: Edges have a direction (A → B).
  • Undirected: Edges have no direction (A ↔ B).
  • Weighted: Edges have weights (values) representing costs, distances, or capacities.
  • Unweighted: Edges have no weights.

Graph Representation

Adjacency Matrix:

  • A 2D array where matrix[i][j] indicates whether there is an edge from node i to node j.
  • In weighted graphs, the value at matrix[i][j] is the weight of the edge.
lightbulbExample

Example for an undirected graph with 3 nodes:

0 1 1
1 0 0
1 0 0

Adjacency List:

  • A list where each node has a sublist of its neighbors.
  • More memory-efficient for sparse graphs.
lightbulbExample

Example:

0: [1, 2]
1: [0]
2: [0]

Graph Traversal

Two primary traversal methods:

Depth-First Search (DFS):

  • Explore as far down one branch as possible before backtracking.
  • Implemented using recursion or a stack.

Breadth-First Search (BFS):

  • Explores all neighbours at the current depth before moving deeper.
  • Implemented using a queue.

Implementing Graphs

Using Arrays (Procedural Approach)

Adjacency Matrix

# Create a graph with 3 nodes using an adjacency matrix
graph = [
    [0, 1, 1],
    [1, 0, 0],
    [1, 0, 0]
]

def add_edge(matrix, u, v):
    matrix[u][v] = 1
    matrix[v][u] = 1  # For undirected graphs

def remove_edge(matrix, u, v):
    matrix[u][v] = 0
    matrix[v][u] = 0  # For undirected graphs

def traverse_matrix(matrix):
    for i, row in enumerate(matrix):
        print(f"Node {i} is connected to: {', '.join(str(j) for j in range(len(row)) if row[j] == 1)}")

Adjacency List

# Graph using an adjacency list
graph = {
    0: [1, 2],
    1: [0],
    2: [0]
}

def add_edge(adj_list, u, v):
    adj_list[u].append(v)
    adj_list[v].append(u)  # For undirected graphs

def remove_edge(adj_list, u, v):
    adj_list[u].remove(v)
    adj_list[v].remove(u)

def traverse_list(adj_list):
    for node in adj_list:
        print(f"Node {node} is connected to: {adj_list[node]}")

Using Object-Oriented Programming (OOP)

lightbulbExample

Example in Python:

class Graph:
    def __init__(self):
        self.adj_list = {}

    def add_node(self, node):
        if node not in self.adj_list:
            self.adj_list[node] = []

    def add_edge(self, u, v):
        if u in self.adj_list and v in self.adj_list:
            self.adj_list[u].append(v)
            self.adj_list[v].append(u)  # For undirected graphs

    def remove_edge(self, u, v):
        if u in self.adj_list and v in self.adj_list:
            self.adj_list[u].remove(v)
            self.adj_list[v].remove(u)

    def dfs(self, start, visited=None):
        if visited is None:
            visited = set()
        visited.add(start)
        print(start, end=" ")
        for neighbor in self.adj_list[start]:
            if neighbor not in visited:
                self.dfs(neighbor, visited)

    def bfs(self, start):
        visited = set()
        queue = [start]
        visited.add(start)
        while queue:
            current = queue.pop(0)
            print(current, end=" ")
            for neighbor in self.adj_list[current]:
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.add(neighbor)

Examples

infoNote

DFS on an Undirected Graph:

g = Graph()
g.add_node(0)
g.add_node(1)
g.add_node(2)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.dfs(0)  # Output: 0 1 2

infoNote

BFS on the Same Graph:

g.bfs(0)  # Output: 0 1 2

Note Summary

infoNote

Common Mistakes

  1. Confusing DFS and BFS:
  • DFS explores depth before breadth, while BFS explores breadth before depth. Ensure correct data structures (stack/recursion for DFS, queue for BFS).
  1. Index Errors in Matrix Implementation:
  • Ensure matrix indices are correctly managed, especially when adding/removing edges.
  1. Not Handling Edge Cases:
  • For empty graphs or isolated nodes, ensure traversal functions handle these scenarios gracefully.
  1. Forgetting to Mark Nodes as Visited:
  • Omitting this step can lead to infinite loops in traversal.
infoNote

Key Takeaways

  • Graphs consist of nodes and edges and can be directed or undirected, weighted or unweighted.
  • Common representations include adjacency matrices and adjacency lists.
  • Two main traversal techniques are DFS and BFS.
  • Practice reading and implementing graph code to understand how to use this versatile data structure effectively.
Books

Only available for registered users.

Sign up now to view the full note, or log in if you already have an account!

500K+ Students Use These Powerful Tools to Master Graphs

Enhance your understanding with flashcards, quizzes, and exams—designed to help you grasp key concepts, reinforce learning, and master any topic with confidence!

90 flashcards

Flashcards on Graphs

Revise key concepts with interactive flashcards.

Try Computer Science Flashcards

9 quizzes

Quizzes on Graphs

Test your knowledge with fun and engaging quizzes.

Try Computer Science Quizzes

29 questions

Exam questions on Graphs

Boost your confidence with real exam questions.

Try Computer Science Questions

27 exams created

Exam Builder on Graphs

Create custom exams across topics for better practice!

Try Computer Science exam builder

12 papers

Past Papers on Graphs

Practice past papers to reinforce exam experience.

Try Computer Science Past Papers

Other Revision Notes related to Graphs you should explore

Discover More Revision Notes Related to Graphs to Deepen Your Understanding and Improve Your Mastery

96%

114 rated

Data Structures

Arrays

user avatar
user avatar
user avatar
user avatar
user avatar

261+ studying

185KViews

96%

114 rated

Data Structures

Records, Lists & Tuples

user avatar
user avatar
user avatar
user avatar
user avatar

253+ studying

195KViews

96%

114 rated

Data Structures

Linked Lists

user avatar
user avatar
user avatar
user avatar
user avatar

403+ studying

200KViews

96%

114 rated

Data Structures

Stacks

user avatar
user avatar
user avatar
user avatar
user avatar

486+ studying

193KViews
Load more notes

Join 500,000+ A-Level students using SimpleStudy...

Join Thousands of A-Level Students Using SimpleStudy to Learn Smarter, Stay Organized, and Boost Their Grades with Confidence!

97% of Students

Report Improved Results

98% of Students

Recommend to friends

500,000+

Students Supported

50 Million+

Questions answered