alg unit ii
alg unit ii
1. GRAPH:
A Graph is a non-linear data structure consisting of vertices and edges. The vertices are
sometimes also referred to as nodes and the edges are lines or arcs that connect any two nodes
in the graph.
A Graph is composed of a set of vertices( V ) and a set of edges( E ). The graph is
denoted by G(V, E).
REPRESENTATIONS OF GRAPH:
Adjacency Matrix
Adjacency List
An adjacency matrix is a way of representing a graph as a matrix of boolean (0’s and 1’s)
Let’s assume there are n vertices in the graph So, create a 2D matrix adjMat[n][n] having
dimension n x n.
Consider an Undirected and Unweighted graph G with 4 vertices and 3 edges. For the graph G,
the adjacency matrix would look like:
1
Here's how to interpret the matrix:
Consider an Undirected and Weighted graph G with 5 vertices and 5 edges. For the graph G, the
adjacency matrix would look like:
Consider an Directed and Unweighted graph G with 4 vertices and 4 edges. For the graph G, the
adjacency matrix would look like:
2
Here's how to interpret the matrix:
Consider an Directed and Weighted graph G with 5 vertices and 6 edges. For the graph G, the
adjacency matrix would look like:
Diagonal Entries: The diagonal entries A[i][i] are usually set to 0 (in case of unweighted) and
INF in case of weighted, assuming the graph has no self-loops.
Undirected Graphs: For undirected graphs, the adjacency matrix is symmetric. This means A[i]
[j] = A[j][i] for all i and j.
An array of Lists is used to store edges between two vertices. The size of array is equal to the
number of vertices (i.e, n).
Let’s assume there are n vertices in the graph So, create an array of list of size n as adjList[n].
adjList[0] will have all the nodes which are connected (neighbour) to vertex 0.
adjList[1] will have all the nodes which are connected (neighbour) to vertex 1 and so on.
3
Representation of Undirected Graph as Adjacency list:
The below undirected graph has 3 vertices. So, an array of list will be created of size 3,
where each indices represent the vertices. Now, vertex 0 has two neighbours (i.e, 1 and 2). So,
insert vertex 1 and 2 at indices 0 of array. Similarly, For vertex 1, it has two neighbour (i.e, 2 and
0) So, insert vertices 2 and 0 at indices 1 of array. Similarly, for vertex 2, insert its neighbours in
array of list.
The below directed graph has 3 vertices. So, an array of list will be created of size 3,
where each indices represent the vertices. Now, vertex 0 has no neighbours. For vertex 1, it has
two neighbour (i.e, 0 and 2) So, insert vertices 0 and 2 at indices 1 of array. Similarly, for vertex
2, insert its neighbours in array of list.
4
2. GRAPH TRAVERSAL:
Graph traversal algorithms are fundamental in graph theory and computer science. They provide
systematic ways to explore graphs, ensuring that each vertex is visited in a specific order. This
systematic approach helps in various tasks like searching, path finding, and analyzing the
connectivity of the graph.
Breadth-First Search (BFS) explores all neighboring vertices before moving to the next level.
BFS uses a queue to keep track of the next vertex to visit. This ensures that all vertices at the
current level are explored before moving to the next level.
BFS is particularly useful for finding the shortest path in an unweighted graph. Since it explores
all nodes at the present depth level before moving on, it guarantees that the first time it reaches
the target node, it has found the shortest path. This makes BFS a go-to algorithm for scenarios
like finding the shortest route in a maze or navigating through a network.
1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweighted
graph, the shortest path is the path with the least number of edges. With Breadth First, we always
reach a vertex from a given source using the minimum number of edges. Also, in the case of
unweighted graphs, any spanning tree is Minimum Spanning Tree and we can use either Depth
or Breadth first traversal for finding a spanning tree.
2. Minimum Spanning Tree for weighted graphs: We can also find Minimum Spanning Tree
for weighted graphs using BFT, but the condition is that the weight should be non-negative and
the same for each pair of vertices.
4. Crawlers in Search Engines: Crawlers build an index using Breadth First. The idea is to start
from the source page and follow all links from the source and keep doing the same. Depth First
Traversal can also be used for crawlers, but the advantage of Breadth First Traversal is, the depth
or levels of the built tree can be limited.
5. Social Networking Websites: In social networks, we can find people within a given distance
‘k’ from a person using Breadth First Search till ‘k’ levels.
6. GPS Navigation systems: Breadth First Search is used to find all neighboring locations.
5
7. Broadcasting in Network: In networks, a broadcasted packet follows Breadth First Search to
reach all nodes.
8. In Garbage Collection: Breadth First Search is used in copying garbage collection using
Cheney’s algorithm. Breadth First Search is preferred over Depth First Search because of a better
locality of reference.
9. Cycle detection in undirected graph: In undirected graphs, either Breadth First Search or
Depth First Search can be used to detect a cycle. We can use BFS to detect cycle in a directed
graph also.
10. Ford–Fulkerson algorithm In Ford – Fulkerson algorithm, we can either use Breadth First
or Depth First Traversal to find the maximum flow. Breadth First Traversal is preferred as it
reduces the worst-case time complexity to O(VE2).
11. To test if a graph is Bipartite: We can either use Breadth First or Depth First Traversal.
12. Path Finding: We can either use Breadth First or Depth First Traversal to find if there is a
path between two vertices.
13. Finding all nodes within one connected component: We can either use Breadth First or
Depth First Traversal to find all nodes reachable from a given node.
14. Network Security: In the field of network security, BFS is used in traversing a network to
find all the devices connected to it.
15. Connected Component: We can find all connected components in an undirected graph.
16. Topological sorting: BFS can be used to find a topological ordering of the nodes in a
directed acyclic graph (DAG).
17. Image processing: BFS can be used to flood-fill an image with a particular color or to find
connected components of pixels.
18. Recommender systems: BFS can be used to find similar items in a large dataset by
traversing the items’ connections in a similarity graph.
Depth-First Search (DFS) explores as far as possible along each branch before backtracking.
DFS uses a stack, either explicitly or through recursion, to keep track of the vertices to visit next.
DFS is useful for detecting cycles and exploring connected components. By diving deep into
each branch, DFS can identify loops in the graph, making it effective for cycle detection.
6
Additionally, DFS can help in identifying all vertices connected to a given vertex, which is
useful in applications like finding clusters in social networks.
1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during
DFS. So we can run DFS for the graph and check for back edges.
2. Path Finding: We can specialize the DFS algorithm to find a path between two given vertices
u and z.
3. Topological Sorting: Topological Sorting is mainly used for scheduling jobs from the given
dependencies among jobs. In computer science, applications of this type arise in instruction
scheduling, ordering of formula cell evaluation when recomputing formula values in
spreadsheets, logic synthesis, determining the order of compilation tasks to perform in makefiles,
data serialization, and resolving symbol dependencies in linkers.
4. To test if a graph is bipartite: We can augment either BFS or DFS when we first discover a
new vertex, color it opposite its parents, and for each other edge, check it doesn’t link two
vertices of the same color. The first vertex in any connected component can be red or black.
6. Solving puzzles with only one solution: such as mazes. (DFS can be adapted to find all
solutions to a maze by only including nodes on the current path in the visited set.).
7. Web crawlers: Depth-first search can be used in the implementation of web crawlers to
explore the links on a website.
9. Model checking: Depth-first search can be used in model checking, which is the process of
checking that a model of a system meets a certain set of properties.
7
GRAPH CONNECTIVITY:
A graph is said to be connected graph if there is a path between every pair of vertex. From every
vertex to any other vertex there must be some path to traverse. This is called the connectivity of a
graph.
A graph is said to be disconnected, if there exists multiple disconnected vertices and edges.
Example
In the above example, it is possible to travel from one vertex to another vertex. Here, we can
traverse from vertex B to H using the path B -> A -> D -> F -> E -> H. Hence it is a connected
graph.
Example
In the above example, it is not possible to traverse from vertex B to H because there is no path
between them directly or indirectly. Hence, it is a disconnected graph.
8
STRONGLY CONNECTED GRAPH:
A strongly connected component of a directed graph is a maximal subgraph where every pair of
vertices is mutually reachable. This means that for any two nodes A and B in this subgraph, there
is a path from A to B and a path from B to A.
For example: The below graph has two strongly connected components {1,2,3,4} and {5,6,7}
since there is path from each vertex to every other vertex in the same strongly connected
component.
Optimizing Web Crawlers: Determining parts of the web graph that are closely linked.
BICONNECTED GRAPH:
An undirected graph is called Biconnected if there are two vertex-disjoint paths between any two
vertices. In a Biconnected Graph, there is a simple cycle through any two vertices.
By convention, two nodes connected by an edge form a biconnected graph, but this does not
verify the above properties. For a graph with more than two vertices, the above properties must
be there for it to be Biconnected.
Or in other words:
9
A graph is said to be Biconnected if:
It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path.
Even after removing any vertex the graph remains connected.
A connected graph is Biconnected if it is connected and doesn’t have any Articulation Point. We
mainly need to check two things in a graph.
A spanning tree is defined as a tree-like subgraph of a connected, undirected graph that includes
all the vertices of the graph. Or, it is a subset of the edges of the graph that forms a tree (acyclic)
where every node of the graph is a part of the tree.
A minimum spanning tree (MST) is defined as a spanning tree that has the minimum weight
among all the possible spanning trees.
10
KRUSKAL’S MINIMUM SPANNING TREE ALGORITHM:
This is one of the popular algorithms for finding the minimum spanning tree from a connected,
undirected graph. This is a greedy algorithm. The algorithm workflow is as below:
Step 2: Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If
the cycle is not formed, include this edge. Else, discard it.
Step 3: Repeat step#2 until there are (V-1) edges in the spanning tree.
The algorithm starts with an empty spanning tree. The idea is to maintain two sets of vertices. The
first set contains the vertices already included in the MST, and the other set contains the vertices
not yet included. At every step, it considers all the edges that connect the two sets and picks the
minimum weight edge from these edges. After picking the edge, it moves the other endpoint of
the edge to the set containing MST.
The working of Prim’s algorithm can be described by using the following steps:
Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST (known as
fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
11