Graphs

Terminology

Data structures for Undirected Graphs

For weighted graphs

Traversal

Can be multiple trees for BFS or DFS

BFS Shortest Path

Pseudocode

Running time

DFS

Same process as BFS but uses a stack

Algorithm

Python

# Using a Python dictionary to act as an adjacency list
graph = {
  '5' : ['3','7'],
  '3' : ['2', '4'],
  '7' : ['8'],
  '2' : [],
  '4' : ['8'],
  '8' : []
}

visited = set() # Set to keep track of visited nodes of graph.

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

# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')

Types of Edges

Edge types

Determining if Cyclic

Distinguishing Cross Edges from Descendant Edges

Time Complexity

Same as BFS

Topological Sort

Algorithm

Ordering

Strongly Connected Components in a Digraph

SCC

Decomposing into SCC Algorithm

  1. dfs_sweep(G) to get finish times for $G$
  2. Compute $G^T$
  3. Call dfs_sweep(G^T) but do it in reversing order from the u.fs from step 1 - this prevents you from crossing SCC boundaries

If you collapse that into a component graph $G^{SCC}$, then you have a DAG and could run Topo Sort

Runs in $\Theta(n)$