0% found this document useful (0 votes)
3 views

Checkpoint_Week_2

The document provides an overview of graph theory, including definitions, types of graphs, and practical applications. It discusses various graph traversal algorithms such as Depth First Search (DFS) and Breadth First Search (BFS), along with shortest path algorithms like Dijkstra’s and Bellman-Ford. Additionally, it covers tree algorithms, minimum spanning trees, and dynamic programming on trees, along with relevant resources and practice problems.

Uploaded by

naveenthumati095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Checkpoint_Week_2

The document provides an overview of graph theory, including definitions, types of graphs, and practical applications. It discusses various graph traversal algorithms such as Depth First Search (DFS) and Breadth First Search (BFS), along with shortest path algorithms like Dijkstra’s and Bellman-Ford. Additionally, it covers tree algorithms, minimum spanning trees, and dynamic programming on trees, along with relevant resources and practice problems.

Uploaded by

naveenthumati095
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

CHECKPOINT

Coding Club, IIT Guwahati

< WEEK 2 >


GRAPH THEORY
A graph is a nonlinear data structure consisting of nodes, called vertices
and lines or arcs connecting the nodes, called edges. More formally, a
graph is composed of a set of vertices(V) and a set of edges(E). Thus, the
graph is denoted by G(V, E).

Practical Applications of Graph Theor


Designing computer networks and developing efficient routing
algorithms for data transmissio
Developing biological networks like gene regulatory networks, et
Very useful in transportation networks for route planning, traffic
optimization, etc

Basic Terminologies in Graph Theor


Vertices : Fundamental units or nodes in a graph, representing
particular entities or states
Edges : Arcs connecting vertices in a graph, represented as an
unordered/ordered pair of vertices according to whether the edge is
undirected/directed respectively
Neighbours : A vertex which is directly reachable from another vertex is
called a neighbour of the latter
Degree(undirected graph) : Number of edges incident to a node is
called its degree
Indegree/Outdegree(directed graph) : Number of incoming edges to
a vertex is called its indegree, while the number of outgoing edges is
called its outdegree.
Types of graph
Undirected graph : Graph where edges do not have a direction
Directed graph : Graph where edges have direction
Connected graph : Graph where every vertex is reachable from every
other vertex
Weighted graph : Graph where every edge is assigned a weight
Directed Acyclic graph : Directed graph without any cycl
Bipartite graph : A graph where the set of vertices can be partitioned
into two subsets such that no two vertices in the same subset have an
edge between them.

Check for bipartite graph : Her


Tree : An undirected connected graph without cycles.

Graph representation
Adjacency matrix : An adjacency matrix of a graph is a two-
dimensional array of size n x n, where n is the number of nodes in the
graph, with the property that a[ i ][ j ] = 1 if the edge (vᵢ, vⱼ) is in the set
of edges, and a[ i ][ j ] = 0 if there is no such edge
Adjacency list : We use an array of lists, where we have n lists, where n
is the number of vertices in the graph. The indices of the lists are the
respective nodes, and each list will store the vertices which are direct
neighbours of the respective vertex.

Refer to the following article for the implementation : Article

Graph traversals

Traversing a graph is visiting all the vertices in the graph. We pick a


starting node and then visit all the nodes reachable from this node. There
are mainly two types of graph traversals, which are depth first
search(DFS) and breadth first search(BFS), both of which differ in the
order of visiting nodes.

Depth First Search:

DFS works by exploring the graph or tree in a depthward motion, meaning


it goes as deep as possible along a branch before moving on to other
branches. The algorithm uses a stack (either explicitly or via recursion) to
keep track of nodes that need to be explored
Start from the source node (or any arbitrary node)
Visit a node and mark it as visited
Move to an unvisited adjacent node and repeat the process
If no unvisited adjacent nodes are left, backtrack and explore any other
unexplored adjacent nodes
Continue this process until all nodes are visited or the target node is
found.

Implementation and applications of DFS : Here

Time complexity of BFS is O(n + m), where n is the number of vertices and
m is the number of edges.

Concept of DFS tree

The DFS tree is one of the most useful techniques for solving graph
structure related questions. It classifies the edges of the graph.

Must read blog on dfs tree : Blog

Breadth First Search:

Breadth First Search (BFS) is another fundamental graph traversal


algorithm that explores all the nodes in a graph or tree level by level. BFS
explores all neighbors of a node before moving on to the next level of
neighbors. BFS is particularly useful for finding the shortest path in an
unweighted graph.

BFS starts at a chosen node (usually the root or any arbitrary node in a
graph) and explores its neighbors. Then it proceeds to the neighbors of
those neighbors, and so on, in a level-by-level manner. BFS uses a
queue data structure to manage the nodes to be explored. This queue
ensures that nodes are processed in the order they are discovered

Start from the root (or any arbitrary node in the case of a
graph)
Visit the node, mark it as visited, and enqueue its neighbors
Dequeue a node, process it, and enqueue its unvisited
neighbors
Repeat the process until all nodes are visited or the target
node is found.

Implementation and finding shortest path using BFS : Here

Multisource BFS

Multisource Breadth First Search (BFS) is a variant of the traditional


BFS algorithm where the traversal starts from multiple source nodes
simultaneously. A common use case is finding the shortest distance
from multiple sources. To implement multisource bfs, we just need to
enqueue all the sources into the queue at the beginning, and then run
the bfs. Read

PROBLEMS FOR DFS, BFS and Multi-source BFS on the following


page

Problems on DFS, BFS and Multi-Source BFS


Counting Room CSE
Labyrinth CSE
Building Roads CSES (Try to solve with both DFS and DSU
Message Route CSE
Building Teams CSE
Round Trip CSE
Monsters CSE
0, 1, 2 Tree
Alex’s whim
Split into Two Set
A Wide, Wide Graph

SHORTEST PATH ALGORITHMS

DJIKSTRA’S ALGORITHM

Dijkstra’s Algorithm is a graph traversal algorithm used to find the

shortest path from a single source node to all other nodes in a weighted

graph. It ensures that the total distance (sum of edge weights) from the

source to each node is minimized.

Key Characteristic

Works on graphs with non-negative weights

Finds the shortest path from a single source to all other nodes

Uses a greedy approach to always expand the nearest unvisited node

Commonly implemented using a priority queue (min-heap) for

efficiency.

These resources will help you to get a better idea on this algorithm :

CPH (pg 126-129

Dijkstra's algorith

Dijkstra Algorithm - Single Source Shortest Path

Problems

Shortest Routes I CSE

Flight Discount CSE

D jikstra

Planet

Paths and Trees

BELLMAN-FORD ALGORITHM

The Bellman-Ford Algorithm is used to find the shortest path from a


single source node to all other nodes in a weighted graph. Unlike
Dijkstra’s Algorithm, Bellman-Ford can handle negative weight edges,
making it useful in graphs where edge weights may be negative.

Key Characteristic
Works on graphs with negative weights, but not on graphs with
negative weight cycles
Uses relaxation to update distances iteratively
Can detect negative weight cycles in a graph
Has a higher time complexity than Dijkstra’s Algorithm, making it less
efficient for large graphs.

RESOURCES

CPH (Page 123-125)

G-41. Bellman Ford Algorithm

PROBLEMS

High Score CSE


All Pair Shortest Pat
Segments - SPOJ

3.Floyd Warshall’s Algorithm:

The Floyd-Warshall Algorithm is a dynamic programming algorithm used

to find the shortest paths between all pairs of nodes in a weighted graph.

Unlike Dijkstra’s and Bellman-Ford, which find the shortest path from a

single source, Floyd-Warshall finds the shortest path between every pair of

nodes in the graph.

Key Characteristic

Works for both directed and undirected graphs

Handles negative weight edges, but not negative weight cycles

Uses a distance matrix instead of an adjacency list

Has a time complexity of O(V³), making it inefficient for large graphs.

These resources will help you to get a better idea on this algorithm with

example and implementation:

CPH (Page 129-131)

G-42. Floyd Warshall Algorithm

Practice Problem

Shortest Routes I

B. Greg and Graph

TREE ALGORITHMS
A tree is a connected, acyclic graph that consists of n nodes and n-1
edges. Moreover, the path between any two nodes of a tree is unique.
Note that since a tree is also a graph, all previous traversal algorithms also
work on it.
Tree Terminology
Root: An arbitrarily chosen node of the tree, considered the "top" of
the structure
Leaf: A node with a degree of 1, meaning it is connected only to one
other node (except in the case of a tree having only 1 node)
Parent: The immediate predecessor of a node along the path from the
node to the root
Ancestors: All the nodes on the path from a given node to the root,
including its parent and its parents ancestors
Subtree: The set of all nodes having the given node as an ancestor
Depth/Level: The distance of a given node from the root of the tre
Diameter: The longest path between any two nodes in a tree. There
can be multiple diameters in a tree
Centre: The middle vertex (or two middle vertices) in the longest path
(diameter) of the tree. Could be different for each diameter in a tree.

Finding a Diameter in a Tree:


There are multiple ways to find a diameter of a tree in O(n). One of the
simplest way is
Run a DFS from any node p and find the farthest node from this node
p. Let a be this node
Now, run a DFS again from this node a and find the farthest node
from the node a. Let b be this node
The path a→b is a diameter of the tree.

The correctness of the algorithm can be found in the resources provided.


RESOURCES

CPH (Page 135-137)

Diameter of a tree and its applications

Practice Problems
Tree Diameter CSE
Tree Distances I CSE
Dynamic Diameter (CF Edu)

Algorithms for Minimum Spanning Tree:


A spanning tree of a graph G is a connected, acyclic subgraph of a
connected graph G consisting of all the nodes of G and some of the
edges of G.

A minimum spanning tree (MST) of a graph G is a spanning tree of


graph G with the lowest total sum of edges among other spanning trees
of graph G


Prim’s Algorithm:

Prim’s algorithm is a method for finding a MST of a graph. The algorithm


first adds an arbitrary node to the tree. After this, the algorithm always
chooses a minimum-weight edge that adds a new node to the tree.
When all the nodes are added to the tree the MST has been found.

RESOURCES

CPH (Page 147-148)

Prim’s algo implementation

Kruskal's Algorithm:

Kruskal’s algorithm is another method to find a MST of a graph. The

algorithm goes through the edges sorted by the edge weight going lower to

higher, and adds an edge to the tree if it does not create a cycle which can

be checked using a data structure called DSU.

Initially, each node of the graph belongs to a separate component. When an

edge is added to the tree, two components are merged into a single

component. Finally, all nodes belong to the same component, forming a

minimum spanning tree in the process.


RESOURCES

CPH (Page 142-145)

Kruskal’s algo implementation

Union Find Data Structure(DSU):

This data structure is used in Kruskal’s Algorithm to efficiently check whether

adding an edge would create a cycle. It maintains a collection of disjoint sets,

ensuring that no element belongs to more than one set.

Each disjoint set is structured as a tree, with one element designated as the

representative (root) of the set. This root serves as the identifier for the set.

Note that if two elements are in the same set, they have the same root.

Two O(logn) time operations are supported by this data structure

Union_Set: Optimally combines the two sets of the given two elements

into a single set or does nothing if both the elements are in the same set

Find_Set: Finds the representative (root) of the set containing the given

element.

RESOURCES

CPH (Page 145-147)

Implementation

Practice Problems:

Building Roads CSE


The Third Lette
Microcycle (HARD
Counting Graphs (HARD)

DP on Trees
Dynamic Programming (DP) on trees is a technique used to efficiently solve
problems involving tree structures by breaking them down into smaller
subproblems, typically in the form of subtrees, and storing intermediate
results to avoid redundant computations.

The transitions in tree DP generally follow two approaches


Bottom-up (Children → Parent): Compute values for child nodes first and
use them to determine the parent’s value
Top-down (Parent → Children): Use precomputed values at the parent to
efficiently compute values for children.

The most popular idea in tree DP is to store subtree properties and analyze
how a child influences its parent or vice versa. Developing this intuition is
essential for effectively applying DP to tree-based problems.

RESOURCES

CF Blog on DP on Trees

Classic Problems
Subordinates CSE
Tree Matching CSE
Tree Diameter CSE
Tree Distances II CSES

Practice Problems
Game on Tree (easy
Game on Tree (medium
Gardening Friend
s s a and Chinchill
K yu h
PermuTree (easy version
Game on Tree (hard) (HARD
Sasha and a Walk in the City(HARD
Vlad and Trouble at MIT (HARD
TREE XOR (HARD
Score of a Tree (HARD)

You might also like