Sei sulla pagina 1di 7

Ques-1 Discuss the following briefly:

a. Representation of graphs

b. Analysis of traversal methods like DFS and BFS

c. Overview about graph searching and traversal

d. Differentiate between BFS and DFS.

A) Graph is a data structure that consists of following two components:


1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v) is not same
as (v, u) in case of a directed graph(di-graph). The pair of the form (u, v) indicates that there is an edge from
vertex u to vertex v. The edges may contain weight/value/cost.

D)
B)Analysis of traversal methods like DFS and BFS

Depth First Search (DFS)

The aim of DFS algorithm is to traverse the graph in such a way that it tries to go far from the root node. Stack is
used in the implementation of the depth first search. Let’s see how depth first search works with respect to the
following graph:

As stated before, in DFS, nodes are visited by going through the depth of the tree from the starting node. If we do
the depth first traversal of the above graph and print the visited node, it will be “A B E F C D”. DFS visits the root
node and then its children nodes until it reaches the end node, i.e. E and F nodes, then moves up to the parent
nodes.

Algorithmic Steps
1. Step 1: Push the root node in the Stack.
2. Step 2: Loop until stack is empty.
3. Step 3: Peek the node of the stack.
4. Step 4: If the node has unvisited child nodes, get the unvisited child node, mark it as traversed and push it on
stack.
5. Step 5: If the node does not have any unvisited child nodes, pop the node from the stack.

Based upon the above steps, the following Java code shows the implementation of the DFS algorithm:

Hide Shrink Copy Code

//
public void dfs()
{
//DFS uses Stack data structure
Stack s=new Stack();
s.push(this.rootNode);
rootNode.visited=true;
printNode(rootNode);
while(!s.isEmpty())
{
Node n=(Node)s.peek();
Node child=getUnvisitedChildNode(n);
if(child!=null)
{
child.visited=true;
printNode(child);
s.push(child);
}
else
{
s.pop();
}
}
//Clear visited property of nodes
clearNodes();
}

//

Breadth First Search (BFS)

This is a very different approach for traversing the graph nodes. The aim of BFS algorithm is to traverse the graph as
close as possible to the root node. Queue is used in the implementation of the breadth first search. Let’s see how
BFS traversal works with respect to the following graph:

If we do the breadth first traversal of the above graph and print the visited node as the output, it will print the
following output. “A B C D E F”. The BFS visits the nodes level by level, so it will start with level 0 which is the root
node, and then it moves to the next levels which are B, C and D, then the last levels which are E and F.

Algorithmic Steps
1. Step 1: Push the root node in the Queue.
2. Step 2: Loop until the queue is empty.
3. Step 3: Remove the node from the Queue.
4. Step 4: If the removed node has unvisited child nodes, mark them as visited and insert the unvisited children in the
queue.

Based upon the above steps, the following Java code shows the implementation of the BFS algorithm:

Hide Copy Code

//
public void bfs()
{
//BFS uses Queue data structure
Queue q=new LinkedList();
q.add(this.rootNode);
printNode(this.rootNode);
rootNode.visited=true;
while(!q.isEmpty())
{
Node n=(Node)q.remove();
Node child=null;
while((child=getUnvisitedChildNode(n))!=null)
{
child.visited=true;
printNode(child);
q.add(child);
}
}
//Clear visited property of nodes
clearNodes();
}
//

The full implementation of this is given in the attached source code.

C)

In computer science, graph traversal (also known as graph search) refers to the process of visiting (checking
and/or updating) each vertex in a graph. Such traversals are classified by the order in which the vertices are
visited. Tree traversal is a special case of graph traversal.

Unlike tree traversal, graph traversal may require that some vertices be visited more than once, since it is not
necessarily known before transitioning to a vertex that it has already been explored. As graphs become more dense,
this redundancy becomes more prevalent, causing computation time to increase; as graphs become more sparse,
the opposite holds true.

Thus, it is usually necessary to remember which vertices have already been explored by the algorithm, so that
vertices are revisited as infrequently as possible (or in the worst case, to prevent the traversal from continuing
indefinitely). This may be accomplished by associating each vertex of the graph with a "color" or "visitation" state
during the traversal, which is then checked and updated as the algorithm visits each vertex. If the vertex has already
been visited, it is ignored and the path is pursued no further; otherwise, the algorithm checks/updates the vertex and
continues down its current path.

Ques 3 Write an Algorithm for Radix Sort. What is the Time complexity.

Radix Sort
Radix sort or bucket sort is a method that can be used to sort a list of a number by its base.
If we want to sort the list of English words, where radix or base is 26 then 26 buckets are used
to sort the words.

To sort an array of decimal number where the radix or base is 10 we need 10 buckets and can
be numbered as 0,1,2,3,4,5,6,7,8,9. A number of passes required to have a sorted array depend
upon the number of digits in the largest element.
Algorithm for Radix sort
Let A be a linear array of n elements A[1], A[2], A[3]............A[n]. Digit is the total number of
digit in the largest element in array A.

1. Input n number of elements in an array A.


2. Find the total number of digits in the largest element in the array.
3. Initialize i=1 and repeat the steps 4 and 5 until( i<=Digit).
4. Initialize the bucket j=0 and repeat the steps 5until (j<n).
5. Compare the ith position of each element of the array with bucket number and place it
in the corresponding bucket.
6. Read the elements (S) of the bucket from 0th bucket to 9th bucket and from the first
position to the higher one to generate new array A.
7. Display the sorted array A.
8. Exit.

Time complexity

Time requirement for the radix sorting method depends on the number of digits and the
elements in the array. Suppose A is an array of n elements A1, A2... An and let r denote the
radix( for example r=10 for decimal digits, r=26 for English letters and r=2 for hits). If A1 is
the largest number then A! Can be represented. Then radix sort require s passes. In passes,
each element is compared with the bucket elements.

So the radix sort requires the total comparison f(n) of: F(n) < = r x s x n

Worst case

In the worst case s = n so F(n) = O(n2)

Best case

In the best case s = logn so f(n) = (nlogn)

Average case

It is very hard to define the time complexity. Because it will depend on the choice of the
radix r and also the number of a digit on largest elements (i.e number of passes) but on an
average (log n) comparison is required so f(n) = O(nlogn)
Ques-4 Explain the 0/1 knapsack problem using dynamic programming.
In 0-1 Knapsack, items cannot be broken which means the thief should take the item as a whole or
should leave it. This is reason behind calling it as 0-1 Knapsack.
Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, where other constraints remain
the same.
0-1 Knapsack cannot be solved by Greedy approach. Greedy approach does not ensure an optimal
solution. In many instances, Greedy approach may give an optimal solution.
Example-1
Let us consider that the capacity of the knapsack is W = 25 and the items are as shown in the following
table.

Item A B C D

Profit 24 18 18 10

Weight 24 10 10 7

Without considering the profit per unit weight (pi/wi), if we apply Greedy approach to solve this problem,
first item A will be selected as it will contribute maximum profit among all the elements.
After selecting item A, no more item will be selected. Hence, for this given set of items total profit is 24.
Whereas, the optimal solution can be achieved by selecting items, B and C, where the total profit is
18 + 18 = 36.
Problem Statement
A thief is robbing a store and can carry a maximal weight of W into his knapsack. There are n items
and weight of ith item is wi and the profit of selecting this item is pi. What items should the thief take?

Dynamic-Programming Approach
Let i be the highest-numbered item in an optimal solution S for W dollars. Then S' = S - {i} is an
optimal solution for W - wi dollars and the value to the solution S is Vi plus the value of the sub-
problem.
We can express this fact in the following formula: define c[i, w] to be the solution for items 1,2, … ,
i and the maximum weight w.
The algorithm takes the following inputs
 The maximum weight W
 The number of items n
 The two sequences v = <v1, v2, …, vn> and w = <w1, w2, …, wn>
Dynamic-0-1-knapsack (v, w, n, W)
for w = 0 to W do
c[0, w] = 0
for i = 1 to n do
c[i, 0] = 0
for w = 1 to W do
if wi ≤ w then
if vi + c[i-1, w-wi] then
c[i, w] = vi + c[i-1, w-wi]
else c[i, w] = c[i-1, w]
else
c[i, w] = c[i-1, w]
The set of items to take can be deduced from the table, starting at c[n, w] and tracing backwards
where the optimal values came from.
If c[i, w] = c[i-1, w], then item i is not part of the solution, and we continue tracing with c[i-1, w].
Otherwise, item i is part of the solution, and we continue tracing with c[i-1, w-W].
Analysis
This algorithm takes θ(n, w) times as table c has (n + 1).(w + 1) entries, where each entry requires
θ(1) time to compute.

Potrebbero piacerti anche