codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

18 / 65 topics
13Binary Search Trees (BSTs)14Balanced Binary Search Trees15AVL Trees16Red-Black Trees17B-Trees18Graphs Basics19Graph Representations (Adjacency List, Matrix)64AVL Trees Advantages and Disadvantages65Red-Black Trees Advantages and Disadvantages
Tutorials/Data Structures & Algorithms/Graphs Basics
🧮Data Structures & Algorithms

Graphs Basics

Updated 2026-04-20
3 min read

Graphs Basics

Graphs are fundamental data structures used in computer science and software engineering for modeling relationships between entities. They consist of nodes (also called vertices) connected by edges, which can be directed or undirected. Understanding graphs is crucial for solving a wide range of problems, including network analysis, social media applications, routing protocols, and more.

Introduction to Graphs

A graph \( G \) is defined as an ordered pair \( G = (V, E) \), where:

  • \( V \) is the set of vertices.
  • \( E \) is the set of edges, each connecting two vertices in \( V \).

Types of Graphs

  1. Undirected Graphs: Edges have no direction. If there's an edge between vertex \( u \) and vertex \( v \), it can be traversed from \( u \) to \( v \) or \( v \) to \( u \).
  2. Directed Graphs (DiGraphs): Edges have a direction. An edge from vertex \( u \) to vertex \( v \) cannot be traversed in the reverse direction.
  3. Weighted Graphs: Each edge has an associated weight or cost, often representing distance, time, or other metrics.
  4. Unweighted Graphs: All edges have equal weights.

Real-World Examples

  • Social Networks: Users are vertices, friendships are edges.
  • Road Maps: Cities are vertices, roads are edges with distances as weights.
  • Computer Networks: Devices are vertices, connections are edges.

Representing Graphs

There are two primary ways to represent graphs in memory:

  1. Adjacency Matrix:

    • A 2D array where the rows and columns represent vertices.
    • \( M[i][j] = 1 \) if there is an edge from vertex \( i \) to vertex \( j \), otherwise \( 0 \).
    • Space complexity: \( O(V^2) \).
  2. Adjacency List:

    • An array of lists, where each list contains the vertices adjacent to a particular vertex.
    • Space complexity: \( O(V + E) \).

Code Example

Here's how you can represent an undirected graph using both adjacency matrix and adjacency list in Python:

# Adjacency Matrix Representation
class GraphMatrix:
    def __init__(self, num_vertices):
        self.num_vertices = num_vertices
        self.matrix = [[0 for _ in range(num_vertices)] for _ in range(num_vertices)]

    def add_edge(self, u, v):
        self.matrix[u][v] = 1
        self.matrix[v][u] = 1

# Adjacency List Representation
class GraphList:
    def __init__(self, num_vertices):
        self.num_vertices = num_vertices
        self.adj_list = [[] for _ in range(num_vertices)]

    def add_edge(self, u, v):
        self.adj_list[u].append(v)
        self.adj_list[v].append(u)

# Usage
matrix_graph = GraphMatrix(5)
matrix_graph.add_edge(0, 1)
matrix_graph.add_edge(0, 2)

list_graph = GraphList(5)
list_graph.add_edge(0, 1)
list_graph.add_edge(0, 2)

Basic Operations on Graphs

Adding an Edge

  • Matrix: Set the corresponding matrix indices to 1.
  • List: Append the vertex to the adjacency list of both vertices (for undirected graphs).

Removing an Edge

  • Matrix: Set the corresponding matrix indices to 0.
  • List: Remove the vertex from the adjacency list of both vertices.

Checking for an Edge

  • Matrix: Check if the matrix value at the given indices is 1.
  • List: Check if the vertex exists in the adjacency list of the other vertex.

Traversing Graphs

Graph traversal involves visiting all vertices and edges. The two main types are:

  1. Depth-First Search (DFS): Explore as far as possible along each branch before backtracking.
  2. Breadth-First Search (BFS): Explore all neighbors at the present depth prior to moving on to nodes at the next depth level.

DFS Implementation

def dfs(graph, start_vertex):
    visited = set()
    stack = [start_vertex]

    while stack:
        vertex = stack.pop()
        if vertex not in visited:
            print(vertex, end=' ')
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    stack.append(neighbor)

# Example usage
graph = {0: [1, 2], 1: [2], 2: [3]}
dfs(graph, 0)  # Output: 0 2 3 1

BFS Implementation

from collections import deque

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

    while queue:
        vertex = queue.popleft()
        if vertex not in visited:
            print(vertex, end=' ')
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    queue.append(neighbor)

# Example usage
graph = {0: [1, 2], 1: [2], 2: [3]}
bfs(graph, 0)  # Output: 0 1 2 3

Best Practices

  • Choose the Right Representation: Use adjacency matrix for dense graphs and adjacency list for sparse graphs.
  • Optimize Traversal: For large graphs, consider using iterative methods instead of recursion to avoid stack overflow.
  • Handle Cycles: Be cautious of cycles in undirected graphs during DFS/BFS to prevent infinite loops.

Conclusion

Graphs are versatile data structures that model complex relationships. Understanding their properties and operations is essential for solving real-world problems efficiently. By choosing the right representation and traversal method, you can optimize performance and resource usage in your applications.


PreviousB-TreesNext Graph Representations (Adjacency List, Matrix)

Recommended Gear

B-TreesGraph Representations (Adjacency List, Matrix)