</>
Skip to content
DSA lessons (24/55)

DSA — Graphs

What is a Graph?

A non-linear data structure consisting of vertices and edges.

class Graph:
    def __init__(self):
        self.adj_list = {}
    
    def add_vertex(self, vertex):
        if vertex not in self.adj_list:
            self.adj_list[vertex] = []
    
    def add_edge(self, v1, v2):
        self.adj_list[v1].append(v2)
        self.adj_list[v2].append(v1)

Graph Types

TypeDescription
DirectedEdges have direction
UndirectedEdges are bidirectional
WeightedEdges have weights
CyclicContains cycles
AcyclicNo cycles

Representation

# Adjacency List
graph = {
    'A': ['B', 'C'],
    'B': ['A', 'D'],
    'C': ['A'],
    'D': ['B']
}

# Adjacency Matrix
matrix = [
    [0, 1, 1, 0],
    [1, 0, 0, 1],
    [1, 0, 0, 0],
    [0, 1, 0, 0]
]

Mini Practice

  1. Implement a graph
  2. Add vertices and edges
  3. Display adjacency list
  4. Check if edge exists

Up Next

Continue with Graph Traversal — traversing graphs.

Related Topics

Frequently Asked Questions about Graphs

What is Graphs in DSA?

Graphs is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Graphs?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Graphs.

Why is Graphs important in DSA?

Graphs is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.