CP League Graphs and Trees
CP League Graphs and Trees
Session 4
Formally, a graph G = (V, E); where V is the vertex set, aka a collection of points and E is
the edge set, or the set of lines joining any two given vertices.
v2
e1
v4
v1 e2
e3 e4
v3
Directed and Undirected Graphs
Directed graph:
The edges in such graphs represent a specific direction.
These graphs have ordered pairs of vertices.
Undirected graph:
The edges in undirected graphs do not have any
specific direction, and can be represented as an
unordered pair of vertices.
Adjacency Matrix
If the graph contains n vertices, the matrix adj[n][n] is defined such that
Adj[i][j] = 1 if there exists an edge between vertex i and vertex j;
Adj[i][j] = 0 if there does not exist an edge between vertices i and j.
Adjacency List
An adjacency list represents a graph as an array of linked lists. The index of the array represents
the vertex, and the nodes of the linked list represent the vertices with which it has an edge.
Some Important Terms
Path: A sequence of vertices and edges of the graph obtained during traversal, such that no
vertex or edge is repeated.
Cycle: Obtained when the graph is traversed such that no vertex or edge is repeated, but the
starting and ending vertices are same.
e1 v2
v4
v1
e2 e4
e3
v3
Connectedness in a Graph
v2
v1 v1 v2
v3
v4 v4 v3
Graph Traversals
Problem
Given a starting vertex, visit all vertices that are reachable from it
Depth First Search (DFS)
Idea
Implementation
Depth First Search (DFS)
Example
6 3 4
2 5
Depth First Search (DFS)
Starting vertex = 1
1
Depth First Search (DFS)
Visited = [1]
6
Depth First Search (DFS)
Visited = [1, 6]
2
Depth First Search (DFS)
Visited = [1, 6, 2]
2
Depth First Search (DFS)
Visited = [1, 6, 2]
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5]
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5]
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5]
6 3
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5, 3]
6 3
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5, 3]
6 3 4
2 5
Depth First Search (DFS)
Visited = [1, 6, 2, 5, 3, 4]
6 3 4
2 5
Depth First Search (DFS)
1. Discover vertices layer by layer, that is, at increasing distances from the starting
vertex s
2. Visit all vertices at a distance k from s before visiting vertices at a distance k + 1.
Breadth First Search (BFS)
Implementation
Breadth First Search (BFS)
Example
1 2 3
4 5 6
Breadth First Search (BFS)
1 2 3
4 5 6
Breadth First Search (BFS)
Queue = [2, 4]
1 2 3
4 5 6
Breadth First Search (BFS)
Queue = [3, 5]
1 2 3
4 5 6
Breadth First Search (BFS)
Queue = [6]
1 2 3
4 5 6
Breadth First Search (BFS)
1 2 3
4 5 6
Breadth First Search (BFS)
BFS in CP problems
1. Mostly used to find the shortest path between two vertices in a graph.
2. Find the diameter of a tree.
Practice problems - 1
1. https://codeforces.com/problemset/problem/277/A
Practice problems - 2