Graph Traversal

Edge Type
Types of Edges[1]
ItemDFSBFS
Data StructureStackQueue
Vertex Orderone sequencetwo sequences
Edge Type (Undirected Graph)tree edge, back edgetree edge, cross edge
Time Complexity (Adjacency Matrix)O(V2)O(V2)
Time Complexity (Adjacency List)O(V+E)O(V+E)
Worst-case Space ComplexityO(V)O(V)

Example

Graph

Adjacency Matrix

0123456
00110000
11011000
21100100
30100100
40011010
50000101
60000010

Adjacency List

  • 0: 1 -> 2
  • 1: 0 -> 2 -> 3
  • 2: 0 -> 1 -> 4
  • 3: 1 -> 4
  • 4: 2 -> 3 -> 5
  • 5: 4 -> 6
  • 6: 5

DFS

def dfs(matrix):
    # taking adjacency matrix
    stack = [0]
    visited = set()
    visited.add(0)
    while stack:
        cur = stack.pop()
        # do something
        print(cur)
        for i, adj in enumerate(matrix[cur]):
            if adj and i not in visited:
                visited.add(i)
                stack.append(i)

BFS

from collections import deque

def bfs(lists):
    # taking adjacency list
    q = deque([0])
    visited = [False] * len(lists)
    visited[0] = True
    while q:
        cur = q.popleft()
        # do something
        print(cur)
        for i in lists[cur]:
            if not visited[i]:
                visited[i] = True
                q.append(i)

Level Order Traversal

from collections import deque

def lot(lists) -> int:
    # taking adjacency list
    q = deque([0])
    visited = [False] * len(lists)
    visited[0] = True
    lv = 0
    while q:
        lv += 1
        print(f'level {lv}')
        for _ in range(len(q)):
            cur = q.popleft()
            # do something
            print(cur)
            for i in lists[cur]:
                if not visited[i]:
                    visited[i] = True
                    q.append(i)
    return lv

Tests


  1. Image is from https://www.geeksforgeeks.org/tarjan-algorithm-find-strongly-connected-components/open in new window ↩︎