You are on page 1of 16

DIGITAL ASSIGNMENT-2

NAME: Shamil Iqbal


REG NO: 18BCA0045

1. In undirected graphs, either Breadth First Search or Depth First Search can
be used to detect cycle. How? Provide reasons and justify your answer with
an example.

We have discussed cycle detection for directed graph. We have also discussed a union-
find algorithm for cycle detection in undirected graphs.. The time complexity of the union-
find algorithm is O(ELogV). Like directed graphs, we can use DFS to detect cycle in an
undirected graph in O (V+E) time. We have discussed DFS based solution for cycle
detection in undirected graph.
In this article, BFS based solution is discussed. We do a BFS traversal of the given graph.
For every visited vertex ‘v’, if there is an adjacent ‘u’ such that u is already visited and u is
not parent of v, then there is a cycle in graph. If we don’t find such an adjacent for any
vertex, we say that there is no cycle. The assumption of this approach is that there are no
parallel edges between any two vertices.

An undirected graph is graph, a set of objects (called vertices or nodes) that are
connected together, where all edges are bidirectional.

Breadth First Traversal (or Search) for a graph is similar to Breadth First Traversal of a
tree (See method 2 of this post). The only catch here is, unlike trees, graphs may contain
cycles, so we may come to the same node again. To avoid processing a node more than
once, we use a boolean visited array. For simplicity, it is assumed that all vertices are
reachable from the starting vertex.
For example, in the following graph, we start traversal from vertex 2. When we come to
vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t
mark visited vertices, then 2 will be processed again and it will become a non-terminating
process. A Breadth First Traversal of the following graph is 2, 0, 3, 1.

Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree.
The only catch here is, unlike trees, graphs may contain cycles, so we may come to the

1
same node again. To avoid processing a node more than once, we use a boolean visited
array.
For example, in the following graph, we start traversal from vertex 2. When we come to
vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don’t
mark visited vertices, then 2 will be processed again and it will become a non-terminating
process. A Depth First Traversal of the following graph is 2, 0, 1, 3.

Depth first search is more memory efficient than breadth first search as you can
backtrack sooner. It is also easier to implement if you use the call stack but this relies on
the longest path not overflowing the stack.
• DFS is easier to implement.
• Once DFS finds a cycle, the stack will contain the nodes forming the cycle.
The same is not true for BFS, so you need to do extra work if you want to also print the
found cycle. This makes DFS a lot more convenient.

2. In directed graph, only depth first search can be used. Why? Provide
reasons and justify your answer with an example.

Depth-first search (DFS) is an algorithm (or technique) for traversing a


graph.
Following are the problems that use DFS as a building block.
1) For an unweighted graph, DFS traversal of the graph produces the minimum
spanning tree and all pair shortest path tree.
2) Detecting cycle in a graph
A graph has 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. (See this for details)
3) Path Finding
We can specialize the DFS algorithm to find a path between two given vertices
u and z.
i) Call DFS(G, u) with u as the start vertex.
ii) Use a stack S to keep track of the path between the start vertex and the
current vertex.
iii) As soon as destination vertex z is encountered, return the path as the
contents of the stack
3. See this for details.
2
4. 4) 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 .
5. 5) To test if a graph is bipartite
We can augment either BFS or DFS when we first discover a new vertex, color it
opposited 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!
See this for details.
6. 6) Finding Strongly Connected Components of a graph A directed graph is called
strongly connected if there is a path from each vertex in the graph to every other
vertex. (See this for DFS based algo for finding Strongly Connected Components)

7) 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.)

use DFS (or any other search) to construct a list of vertices reachable from the starting
vertex. Do this silently, print nothing. Then find a vertex V in the list such that there is no
edge from a vertex in the list to V, print V, and remove V from the list. Repeat this step
until the list is empty.
1 Depth First Search in Directed Graphs
Let tt = ( V, E) be a directed graph, where V is the vertex set and E is the edge
set. We assume the graph is represented as an adjacency structure, that is,
for every vertex v there is a set adj(v) which is the set of vertices reachable
by following one edge out of v. To do a depth first search we keep two pieces
of information associated with each vertex v. One is the depth first search
numbering num(v), and the other is mark(v), which indicates that v is
currently on the recursion stack.
Here is the depth first search procedure:
i←0
for all v ∈ V do num(v) ← 0
for all v ∈ V do mark(v) ←
0 for all v ∈ V do
if num(v) = 0 then DFS(v)

DFS(v)
i←i+1
num(v) ← i
mark(v) ←
1
for all w ∈ adj(v) do
if num(w) = 0 then DFS(w) [(v, w) is a tree edge]

3
else if num(w) > num(v) then [(v, w) is a forward
edge] else if mark(w) = 0 then [(v, w) is a cross
edge]
else [(v, w) is a back edge]
mark(v) ←
0 end DFS

This process examines all the edges and vertices. The call DFS( v) is made
exactly once for each vertex in the graph. Each edge is placed into exactly
one of four classes by the algorithm: tree edges, forward edges, cross
edges and back edges.

4
This classification of the edges is not a property of the graph alone. It also
depends on the ordering of the vertices in adj(v) and on the ordering of the
vertices in the loop that calls the DFS procedure. The num and mark fields
are not actually necessary to accomplish a complete search of the graph.
All that is needed to do that is a single bit for each vertex that indicates
whether or not that vertex has already been searched. (This bit is zero for
vertex v if and only if num(v) = 0.) We have presented the fully general
version here because it is needed for the strong components algorithm
that we present later in this lecture.
The tree edges have the property that either zero or one of them points to
a given vertex. (It’s the edge used to discover a vertex for the first time.)
Therefore, they define a collection of trees, called the depth first spanning
forest of the graph. The root of each tree is the lowest numbered vertex in
it (the one that was searched first). These rooted trees allow us to define
the ancestor and descendant relations among vertices.

3. In GPS Navigation System, Breadth First Search is being used. Why? Why not
Depth First Search. Find Reasons and justify your answer.

GPS in BFS:

There are differences in the route which I usually take and the one which GPS shows as
the shortest, probably due to the algorithms used. I learned from my graph theory data
structure classes that (BFS) Breadth First search example is GPS navigation and digital
maps. I tried looking for the possible use of Algorithms (Breadth First Search example
or A* application) used in GPS navigation on the web, but I couldn’t find a lot of details.
So here is how Breadth First Search is used in real life application like GPS.

Let’s first understand working of GPS navigation

Digital maps, unlike humans, see streets as a bunch of nodes. The 2.6-mile road from
the Columbus Circle station (59 st) to Cathedral Pkwy (110 st) is called Central Park
West. We (humans) consider this road a single entity (You may divide it into few more
segments based on metro stations or intersections, but not more than that).
5
There are differences in the route which I usually take and the one which GPS
shows as the shortest, probably due to the algorithms used. I learned from my
graph theory data structure classes that (BFS) Breadth First search example is GPS
navigation and digital maps. I tried looking for the possible use of Algorithms
(Breadth First Search example or A* application) used in GPS navigation on the
web, but I couldn’t find a lot of details. So here is how Breadth First Search is used
in real life application like GPS.
Let’s first understand working of GPS navigation
Digital maps, unlike humans, see streets as a bunch of nodes. The 2.6-mile road
from the Columbus Circle station (59 st) to Cathedral Pkwy (110 st) is called Central
Park West. We (humans) consider this road a single entity (You may divide it into
few more segments based on metro stations or intersections, but not more than
that).
But a GPS navigation or any other digital map divides it into hundreds of segments,
with some only 24 meters long. A GPS looks at this street as a graph divided into
vertices and edges.
Considering this, there is a lot of data to be covered and calculated while finding
the shortest path.
Before we begin you must know the answers to the following:
graph
A graph usually looks like the image below and is made up of vertices and edges
(represented by lines and circles, respectively).

The objective of a graph is to represent a problem as a set of points that are


connected in various ways using edges. With the help of such graphs, we tend to
solve our problems by applying various algorithms.
Let’s take an example to understand better.
Facebook is a good example to understand graph theory.
Facebook has millions of users. If a person needs to find a friend, he can use
an array and search. But that would take a lot of time and memory to search for so
many people, making the problem quite complex.
But if the same scenario is represented using a graph, the problems tend to get
solved easily. With a graph, you know that these two people are actually
friends(Though real-life scenarios are not exactly that simple!).Check this video on
how graph theory is used in social networks
Graph theories are frequently used in various other fields, such as maps, e-
commerce, and computer games.
Before we go further down this road, read this detailed article about graph theory,
which explains other important aspects of Graphs such as Directed, Undirected,
Cycle or Loop, and Matrix.
Breadth First Search and working
Depth First Search (DFS) and Breadth First Search (BFS) are algorithms, or in
simple terms, they are methods to traverse a graph.
Before I explain Breadth First Search, consider this example.
Take a graph with 13 nodes. When Breadth First Search is applied to this graph,
the algorithm traverses from node 1 to node 2 and then to nodes 3, 4, 5,v6 (in
green) and so on in the given order.
If you consider 1 (in red) as the first node, you observe that Breadth First Search
gradually moves outward, considering each neighboring node first.

6
4.
Consider any graph with minimum of 8 nodes and all the nodes are connected
without any isolated node. Find all the possible paths between any two nodes
among them. Implement a suitable program to print the same.

POSSIBLE PATHS (BETWEEN 2 & 4):

• 2-> 0-> 1-> 3-> 4

• 2 ->0-> 3-> 4

• 2 ->1-> 3-> 4

• 2 ->5-> 6-> 4

PROGRAM:

#include<iostream>

#include<list>

using namespace std;

class Graph

int V; // No. of vertices in graph

list<int> *adj; // Pointer to an array containing adjacency


lists void printAllPathsUtil(int , int , bool [], int [], int &);
public:

Graph(int V); // Constructor

void addEdge(int u, int v);

void printAllPaths(int s, int d);

};
7
Graph::Graph(int V)

this->V = V;

adj = new list<int>[V];

void Graph::addEdge(int u, int v)

adj[u].push_back(v); // Add v to u’s list.

void Graph::printAllPaths(int s, int d)

bool *visited = new bool[V];

int *path = new int[V];

int path_index = 0; // Initialize path[] as empty


for (int i = 0; i < V; i++)

8
visited[i] = false;

printAllPathsUtil(s, d, visited, path, path_index);

void Graph::printAllPathsUtil(int u, int d, bool visited[],int path[],


int &path_index)

visited[u] = true;

path[path_index] = u;

path_index++;

if (u == d)

for (int i = 0; i<path_index; i++)

cout << path[i] << " ";

cout << endl;

else // If current vertex is not destination

list<int>::iterator i;

for (i = adj[u].begin(); i != adj[u].end(); ++i)

if (!visited[*i])

printAllPathsUtil(*i, d, visited, path, path_index);

9
}

path_index--;

visited[u] = false;

int main()

Graph g(8);

g.addEdge(0, 1);

g.addEdge(0, 2);

g.addEdge(0, 3);

g.addEdge(2, 0);

g.addEdge(2, 1);

g.addEdge(1, 3);

g.addEdge(2,5);

g.addEdge(5,2);

g.addEdge(5,6);

g.addEdge(6,5);

1
0
g.addEdge(6,4);

g.addEdge(4,6);

g.addEdge(4,7);

g.addEdge(7,4);

g.addEdge(4,3);

g.addEdge(3,4);

int s,d;

cout<<"Enter source:";

cin>>s;

cout<<"Enter destination:";

cin>>d;

cout << "Following are all different paths from "<<s << "to"<<d<<endl;

g.printAllPaths(s,d);

return 0;

1
1
5.
Discuss the applications of Binary Tree and Binary Search Tree with a
suitable real time example.

Applications of Binary Tree:


• Binary Search Tree - Used in many search applications where data is
constantly entering/leaving, such as the map and set objects in many
languages' libraries.
• Binary Space Partition - Used in almost every 3D video game to determine
what objects need to be rendered.
• Binary Tries - Used in almost every high-bandwidth router for storing
router-tables.
• Hash Trees - used in p2p programs and specialized image-signatures in
which a hash needs to be verified, but the whole file is not available.
• Heaps - Used in implementing efficient priority-queues, which in turn are
used for scheduling processes in many operating systems, Quality-of-
Service in routers, and A* (path-finding algorithm used in AI applications,
including robotics and video games). Also used in heap-sort.
• Huffman Coding Tree (Chip Uni) - used in compression algorithms,
such as those used by the .jpeg and .mp3 file-formats.
• GGM Trees - Used in cryptographic applications to generate a tree of
pseudo-random numbers.
• Syntax Tree - Constructed by compilers and (implicitly) calculators to
parse expressions.
• Treap - Randomized data structure used in wireless networking and
memory allocation.
• T-tree - Though most databases use some form of B-tree to store data on
the drive, databases which keep all (most) their data in memory often use
T-trees to do so.
• Routing - used in network routing
• Hierarchical data - used in manipulating hierarchical data.
• Expression - used by compilers and (implicitly) calculators to
parse expressions.
• Database Cluster - clusters are keyed with balanced binary tree or hashtable.
• Decision Tree - a decision tree can also represent a series of steps taken
by an algorithm.
• To squabble about the performance of binary-trees is meaningless - they are
not a data structure, but a family of data structures, all with different
performance characteristics. While it is true that unbalanced binary trees

1
2
perform much worse than self-balancing binary trees for searching, there are
many binary trees (such as binary tries) for which "balancing" has no meaning.

• The reason that binary trees are used more often than n-ary trees for
searching is that n-ary trees are more complex, but usually provide no real
speed advantage.
In a (balanced) binary tree with m nodes, moving from one level to the next requires one
comparison, and there are log_2(m) levels, for a total of log_2(m) comparisons. In
contrast, an n-ary tree will it will require log_2(n) comparisons (using a binary search)
to move to the next level. Since there are log_n(m) total levels, the search will require
log_2(n)*log_n(m) = log_2(m) comparisons total. So, though n-ary trees are more
complex, they provide no advantage in terms of total comparison.

Real World Example:

Real world example (on daily basis) of binary trees which I could think of is

1) family tree.

2) any decision you make (For ex if you want to go to

movie-here would be binary tree :

3) In general, binary trees are used as an efficient means of representing


hierarchical data, or as a way of storing data in a searchable format.
4) Database Indices- When you index a field, it is put in a binary tree for
fast retrieval.
5) Sorting algorithms
6) Parsers
7) Red–black tree are used in the Linux Kernel in the scheduler,process
abstraction(for file description management) and virtual memory
system.
8) JPEG encoders use Huffman coding sorted binary tree.
9) Most decision-making process can be represented as a binary tree. At
each node of the tree a yes/no decision is made on some issue. a path
from root to leaf in this tree represents a chain of decisions which were
made to arrive at some course of action.

Application of Binary Search Tree:

1
3
Binary Search Tree, is a node-based binary tree data structure which has the
following properties:

• The left subtree of a node contains only nodes with keys lesser than the node’s
key.
• The right subtree of a node contains only nodes with keys greater than the node’s
key.
• The left and right subtree each must also be a binary search
tree. There must be no duplicate nodes.

1
4
1
5
1
6

You might also like