0% found this document useful (0 votes)
119 views35 pages

DAA Unit-3 Course Material

This document provides course material for the Design and Analysis of Algorithms unit covering basic traversal and search techniques for binary trees and graphs. It includes: 1. An introduction and objectives of the unit along with prerequisites and syllabus. 2. Details of various traversal techniques for binary trees including in-order, post-order and pre-order traversals. 3. Explanations and examples of traversal and search techniques for graphs including connected components, spanning trees, and depth-first search. 4. An outline of topics to be covered in the unit including backtracking, the 8-queens problem, subset sums, graph coloring, and the knapsack problem.

Uploaded by

Priya Kolaparthy
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)
119 views35 pages

DAA Unit-3 Course Material

This document provides course material for the Design and Analysis of Algorithms unit covering basic traversal and search techniques for binary trees and graphs. It includes: 1. An introduction and objectives of the unit along with prerequisites and syllabus. 2. Details of various traversal techniques for binary trees including in-order, post-order and pre-order traversals. 3. Explanations and examples of traversal and search techniques for graphs including connected components, spanning trees, and depth-first search. 4. An outline of topics to be covered in the unit including backtracking, the 8-queens problem, subset sums, graph coloring, and the knapsack problem.

Uploaded by

Priya Kolaparthy
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/ 35

SVCE KADAPA

COURSE MATERIAL

DESIGN AND ANALYSIS OF


SUBJECT ALGORITHMS (15A05604)

UNIT 3

COURSE B.TECH

COMPUTER SCIENCE AND


DEPARTMENT ENGINEERING

SEMESTER 3-2

PREPARED BY M Ravi Prasad


(Faculty Name/s) Sr. Assistant Professor

Version V-1

PREPARED / REVISED DATE 05-04-2021

31|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

TABLE OF CONTENTS – UNIT 3


S. NO CONTENTS PAGE NO.
1 COURSE OBJECTIVES 3
2 PREREQUISITES 3
3 SYLLABUS 3
4 COURSE OUTCOMES 3
5 CO - PO/PSO MAPPING 3
6 LESSON PLAN 4
7 ACTIVITY BASED LEARNING 4
8 LECTURE NOTES 4
1.1 INTRODUCTION 2
1.2 TECHNIQUES FOR BINARY TREES
1.3 TECHNIQUES FOR GRAPHS 8
1.4 CONNECTED COMPONENTS AND SPANNING TREES 19
1.5 BI-CONNECTED COMPONENTS AND DFS 12

1.6 BACK TRACKING: GENERAL METHOD, 23


1.7 8 – QUEENS PROBLEM 24
1.8 SUM OF SUBSETS PROBLEM 25
1.9 GRAPH COLORING 26
1.10 HAMILTONIAN CYCLES 27
1.11 KNAPSACK PROBLEM 30
9 PRACTICE QUIZ 31
10 ASSIGNMENTS 33
11 PART A QUESTIONS & ANSWERS (2 MARKS QUESTIONS) 33
12 PART B QUESTIONS 34
13 SUPPORTIVE ONLINE CERTIFICATION COURSES 35
14 REAL TIME APPLICATIONS 35
15 CONTENTS BEYOND THE SYLLABUS 35
16 PRESCRIBED TEXT BOOKS & REFERENCE BOOKS 36
17 MINI PROJECT SUGGESTION 37

32|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

1. Course Objectives
1. To demonstrate the importance of algorithms in computing.
2. To explain the analysis of algorithms
3. To illustrate the method of finding the complexity of algorithms
4. To explain the advanced algorithm design and analysis techniques.
5. To introduce special classes of algorithms NP – completeness and the classes P
and NP.

2. Prerequisites
Students should have knowledge on
1. Students should have basic knowledge on graphs
2. They should have basic data structure’s knowledge.

3. Syllabus
UNIT III
Basic Traversal and Search Techniques: Techniques for binary trees, Techniques for Graphs,
Connected components and Spanning trees, Bi-connected components and DFS

Back tracking: General Method, 8 – queens problem, Sum of subsets problem, Graph coloring and
Hamiltonian cycles, Knapsack Problem.

4. Course outcomes

1. Determine the time complexity of an algorithm by solving the corresponding


recurrence equation
2. Analyze the LC and FIFO branch and bound solutions for optimization problems,
and compare the time complexities with Dynamic Programming techniques.
3. Define and Classify deterministic and Non-deterministic algorithms; P, NP, NP –hard
And NP-complete classes of problems.
4. Apply Backtracking technique for solving constraint satisfaction problems.

5. Co-PO / PSO Mapping

DAA PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 P10 PO11 PO12 PSO1 PSO2

CO1 3 3 2 2

CO2 3 3 2 2

CO3 3 3 2 2

CO4 3 3 2 2

CO5 3 3 2 2

33|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

5. Lesson Plan
Lecture No. Weeks Topics to be covered References

1 Techniques for binary trees T1

2 Techniques for Graphs T1, R1

3 1 Connected components and Spanning trees T1, R1

4 Bi-connected components and DFS T1, R1

5 Back tracking: General Method, T1, R2

6 8 – queens problem T1, R1

7 2 Sum of subsets problem T1, R1

8 Graph coloring T1, R1

9 Hamiltonian cycles T1, R1


3
10 Knapsack Problem T1, R1

7. Activity Based Learning


1. Practice different types of problems on graph.
2. Performing different types of graph search method on binary trees.
8. Lecture Notes
1.1 INTRODUCTION
A Binary Search tree is organized in a Binary Tree. Such a tree can be defined by a
linked data structure in which a particular node is an object. In addition to a key
field, each node contains field left, right, and p that point to the nodes
corresponding to its left child, its right child, and its parent, respectively. If a child or
parent is missing, the appropriate field contains the value NIL. The root node is the
only node in the tree whose parent field is Nil.
• Definition 1 Traversal of a binary tree involves examining every node in the tree.
• Definition 2 Search involves visiting nodes in a graph in a systematic manner, and
may or may not result into a visit to all nodes.
• Different nodes of a graph may be visited, possibly more than once, during traversal
or search
• If search results into a visit to all the vertices, it is called traversal
• When traversing a binary tree, we need to follow linear order i.e. L, D, R where
• L->Moving left
• D->printing the data R->moving right
• We have three traversal techniques on binary tree. They are

34|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

• In order
• Post order
• Pre order

Examples

In order: A-B-C-D-E-F-G-H-I

Post order: A-C-E-D-B-H-I-G-F

Pre order: F-B-A-D-C-E-G-I-H

For fig: Graph

Preorder, post order and in order algorithms Algorithm


Input: x is the root of a sub tree.
If x ≠ NULL
Then output key(x);
Preorder (left(x));
Preorder (right(x));
Algorithm postorder(x)
Input: x is the root of a subtree
If x ≠ NULL
35|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
Algorithm postorder(x)
Input: x is the root of a subtree
If x ≠ NULL
Then postorder(left(x));;
Postorder(right(x));
Outputkey(x);

Fig: a) Preorder b) post order

Algorithm inorder(x)
Input: x is the root of a subtree
If x≠ null
Then inorder(left(x));
Outputkey(x);
Inorder(right(x));

Fig: c) inorder

36|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
Exercise

37|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
3.1 TECHNIQUES FOR GRAPHS
• Graph: The sequence of edges that connected two vertices. A graph is a pair (V,
E), where
• V is a set of nodes, called vertices
• E is a collection (can be duplicated) of pairs of vertices, called edges Vertices and
edges are data structures and store elements.
• Types of graphs: Graphs are of three types.
• Directed/Undirected: In a directed graph the direction of the edges must be
considered

Fig: Directed Graph Fig: Undirected Graph

Weighted/ Un weighted: A weighted graph has values on its edge.

Fig:Un weighted graph


Fig: Weighted Graph

38|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

Cyclic/Acyclic: A cycle is a path that begins and ends at same vertex and A graph with
no cycles is acyclic.

Fig: Cyclic Graph Fig: Acyclic graph

3.1.1 REPRESENTATION OF GRAPHS


Graphs can be represented in three ways:

1. Adjacency Matrix: A V x V array, with matrix[i][j] storing whether there is an edge


between the ith vertex and the jth vertex. This matrix is also called as “Bit matrix” or
“Boolean Matrix”

39|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

2. Adjacency list: One linked list per vertex, each storing directly reachable vertices .

3. Linked List or Edge list

3.1.2 GRAPH TRAVERSAL TECHNIQUES


Graph traversal techniques
“The process of traversing all the nodes or vertices on a graph is called graph
traversal”. We have two traversal techniques on graphs DFS BFS

310|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
3.1.2.1 Depth First Search
The DFS explore each possible path to its conclusion before another path is tried. In
other words go as a far as you can (if u don’t have a node to visit), otherwise, go back
and try another way. Simply it can be called as “backtracking”.
Steps for DFS
1. Select an unvisited node ‘v’ visits it and treats it as the current node.
2. Find an unvisited neighbor of current node, visit it and make it new current node
If the current node has no unvisited neighbors, backtrack to its parent and make it
As a new current node
3. Repeat steps 2 and 3 until no more nodes can be visited
4. Repeat from step 1 for remaining nodes also.
Implementation of DFS DFS (Vertex)

{
Mark u as visiting
For each vertex V directly reachable from u
If v is unvisited DFS (v)
}

311|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
• Unexplored vertex: The node or vertex which is not yet visited.
• Visited vertex: The node or vertex which is visited is called ‘visited vertex’ i.e. can be
called as “current node”.
• Unexplored edge: The edge or path which is not yet traversed.
• Discovery edge: It is opposite to unexplored edge, the path which is already
traversed is known as discovery edge.
• Back edge: If the current node has no unvisited neighbors we need to backtrack to
its parent node. The path used in back tracking is called back edge.
For the following graph the steps for tracing are as follows:

312|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

PROPERTIES OF DFS
• DFS (G, v) visits all the vertices and edges in the connected component of v.
• The discovery edges labeled by DFS (G, v) form a spanning tree of the connected
component of v.
• Tracing of graph using Depth First Search

313|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

3.1.2.2 Breadth First Search


• It is one of the simplest algorithms for searching or visiting each vertex in a graph. In
this method each node on the same level is checked before the search proceeds
to the next level. BFS makes use of a queue to store visited vertices, expanding the
path from the earliest visited vertices
• Breadth: a-b-c-d-e-f-g-h-i-j-k
• Steps for BFS:
• Mark all the vertices as unvisited.
• Choose any vertex say ‘v’, mark it as visited and put it on the end of the queue.
• Now, for each vertex on the list, examine in same order all the vertices adjacent to
‘v’
• When all the unvisited vertices adjacent to v have been marked as visited and put
it on the end (rear of the queue) of the list.
• Remove a vertex from the front of the queue and repeat this procedure.
• Continue this procedure until the list is empty.
314|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

IMPLEMENTATION OF BFS

• While queue Q not empty


• De queue the first vertex u from Q
• For each vertex v directly reachable from u
• If v is unvisited En queue v to Q Mark v as visited
• 1 Initially all vertices except the start vertex are marked as unvisited and the queue
contains the start vertex only.
Explored vertex: A vertex is said to be explored if all the adjacent vertices of v are visited.
Example 1: Breadth first search for the following graph.

315|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

316|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

PROPERTIES OF BFS
Notation: Gs (connected component of s)
• BFS (G, s) visits all the vertices and edges of Gs
• The discovery edges labeled by BFS (G, s) form a spanning tree Ts of G
• For each vertex v in Li
• The path of Ts from s to v has i edges
• Every path from s to v in Gs has at least i edges.

317|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
COMPLEXITY OF BFS
• Step1: read a node from the queue O (v) times.
• Step2: examine all neighbors, i.e. we examine all edges of the currently read node.
Not oriented graph: 2*E edges to examine
• Hence the complexity of BFS is O (V + 2*E)
• Tracing of graph using Breadth first search

318|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

1.4 CONNECTED COMPONENTS AND SPANNING TREES

• Connected component: If G is connected undirected graph, then we can visit all


the vertices of the graph in the first call to BFS. The sub graph which we obtain after
traversing the graph using BFS represents the connected component of the graph.

Thus BFS can be used to determine whether G is connected. All the newly visited vertices
on call to BFS represent the vertices in connected component of graph G. The sub
graph formed by theses vertices make the connected component.
• Spanning tree of a graph: Consider the set of all edges (u, w) where all vertices w
are adjacent to u and are not visited. According to BFS algorithm it is established
that this set of edges give the spanning tree of G, if G is connected. We obtain
depth first search spanning tree similarly
• These are the BFS and DFS spanning trees of the graph G

319|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

1.5 Bi-connected Components &DFS


• A connected undirected graph is said to be bi-connected if it remains connected
after removal of any one vertex and the edges that are incident upon that vertex.
• In this we have two components.
• Articulation point: Let G= (V, E) be a connected undirected graph. Then an
articulation point of graph ‘G’ is a vertex whose articulation point of graph is a
vertex whose removal disconnects the graph ‘G’. It is also known as “cut point”.
• Bi-connected graph: A graph ‘G’ is said to be bi-connected if it contains no-
articulation point.

Articulation points for the above undirected graph are B, E, F

i) After deleting vertex B and incident edges of B, the given graph is divided into two
components

320|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

ii) After deleting the vertex E and incident edges of E, the resulting components are

iii) After deleting vertex F and incident edges of F, the given graph is divided into teo
components.

Note: If there exists any articulation point, it is an undesirable feature in communication


network where joint point between two networks failure in case of joint node fails.

321|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

Algorithm to construct the Bi- Connected graph

• For each articulation point ‘a’ do


• Let B1, B2, B3 ….Bk are the Bi-connected components
• Containing the articulation point ‘a’
• Let Vi E Bi, Vi # a i<=i<=k
• Add (Vi,Vi+1) to Graph G. Vi-vertex belong Bi
• Bi-Bi-connected component
• i- Vertex number 1 to k a- articulation point

1.5 BACKTRACKING: GENERAL METHOD

Backtracking is used to solve problem in which a sequence of objects is chosen from a


specified set so that the sequence satisfies some criterion. The desired solution is
expressed as an n-tuple (x1, . . . . , xn) where each xi Є S, S being a finite set.

322|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
The solution is based on finding one or more vectors that maximize, minimize, or satisfy a
criterion function P (x1, ......... , xn).

Form a solution and check at every step if this has any chance of success. If the solution
at any point seems not promising, ignore it. All solutions requires a set of constraints
divided into two categories: explicit and implicit constraints.

• Definition 1: Explicit constraints are rules that restrict each xi to take on values only
from a given set. Explicit constraints depend on the particular instance I of
problem being solved. All tuples that satisfy the explicit constraints define a possible
solution space for I.

• Definition 2: Implicit constraints are rules that determine which of the tuples in the
solution space of I satisfy the criterion function. Thus, implicit constraints describe
the way in which the xi‟s must relate to each other.

1.7 8-QUEENS PROBLEM

Explicit constraints using 8-tuple formation, for this problem are S= {1, 2, 3, 4, 5, 6, 7, 8}.

The implicit constraints for this problem are that no two queens can be the same (i.e., all
queens must be on different columns) and no two queens can be on the same diagonal.

Backtracking is a modified depth first search of a tree. Backtracking algorithms determine


problem solutions by systematically searching the solution space for the given problem
instance. This search is facilitated by using a tree organization for the solution space.

Backtracking is the procedure where by, after determining that a node can lead to
nothing but dead end, we go back (backtrack) to the nodes parent and proceed with
the search on the next child.

A backtracking algorithm need not actually create a tree. Rather, it only needs to keep
track of the values in the current branch being investigated. This is the way we
implement backtracking algorithm. We say that the state space tree exists implicitly in
the algorithm because it is not actually constructed.

1.7.1. TERMINOLOGY

• Problem state is each node in the depth first search tree.


• Solution states are the problem states „S‟ for which the path from the root node to
„S‟ defines a tuple in the solution space.
• Answer states are those solution states for which the path from root node to s
defines a tuple that is a member of the set of solutions.

• State space is the set of paths from root node to other nodes. State space tree is
the tree organization of the solution space. The state space trees are called static
323|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
trees. This terminology follows from the observation that the tree organizations are
independent of the problem instance being solved. For some problems it is
advantageous to use different tree organizations for different problem instance.
• In this case the tree organization is determined dynamically as the solution space is
being searched. Tree organizations that are problem instance dependent are
called dynamic trees.
• Live node is a node that has been generated but whose children have not yet
been generated.
• E-node is a live node whose children are currently being explored. In other words,
an E-node is a node currently being expanded.
• Dead node is a generated node that is not to be expanded or explored any
further. All children of a dead node have already been expanded
• Branch and Bound refers to all state space search methods in which all children of
an E-node are generated before any other live node can become the E-node.
• Depth first node generation with bounding functions is called backtracking. State
generation methods in which the E-node remains the E-node until it is dead, lead
to branch and bound methods.
1.8 SUM OF SUBSETS
• Given positive numbers wi, 1 ≤ i ≤ n, and m, this problem requires finding all subsets
of wi whose sums are „m‟.
• All solutions are k-tuples, 1 ≤ k ≤ n. Explicit constraints:
• xi Є {j | j is an integer and 1 ≤ j ≤ n}.
• Implicit constraints:
• No two xi can be the same.
• The sum of the corresponding wi‟s be m.
• xi < xi+1 , 1 ≤ i < k (total order in indices) to avoid generating multiple instances of
the same subset (for example, (1, 2, 4) and (1, 4, 2) represent the same subset).
• A better formulation of the problem is where the solution subset is represented by
an n- tuple (x1,......... , xn) such that xi Є {0, 1}.
• The above solutions are then represented by (1, 1, 0, 1) and (0, 0, 1, 1). For both the
above formulations, the solution space is 2n distinct tuples.
• For example, n = 4, w = (11, 13, 24, 7) and m =
• 31, the desired subsets are (11,
• 13, 7) and (24, 7).

324|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

1.9 GRAPH COLORING (FOR PLANAR GRAPHS)

• Let G be a graph and m be a given positive integer. We want to discover whether


the nodes of G can be colored in such a way that no two adjacent nodes have
the same color, yet only m colors are used. This is termed the m-colorabiltiy
decision problem.
• The m-colorability optimization problem asks for the smallest integer m for which
the graph G can be colored.
• Given any map, if the regions are to be colored in such a way that no two
adjacent regions have the same color, only four colors are needed.
• For many years it was known that five colors were sufficient to color any map, but
no map that required more than four colors had ever been found. After several
hundred years, this problem was solved by a group of mathematicians with the
help of a computer. They showed that in fact four colors are sufficient for planar
graphs.
• The function m-coloring will begin by first assigning the graph to its adjacency
matrix, setting the array x [] to zero. The colors are represented by the integers 1, 2.
• m and the solutions are given by the n-tuple (x1, x2, . ., xn), where xi is the color of
node i.
• A recursive backtracking algorithm for graph coloring is carried out by invoking the
statement mcoloring(1)

Algorithm mcoloring (k)

• // This algorithm was formed using the recursive backtracking schema.

325|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
• The graph is
• // represented by its Boolean adjacency matrix G [1: n, 1: n]. All assignments of
• // 1, 2, . . . . . , m to the vertices of the graph such that adjacent vertices are
assigned
• // distinct integers are printed. k is the index of the next vertex to color.
• {
• repeat
• { // Generate all legal assignments for x[k].
• NextValue (k); // Assign to x [k] a legal color. If (x [k] = 0) then return; // No new
color possible If (k = n) then // at most m colors have been
• // used to color the n vertices.
• write (x [1: n]);
• else mcoloring (k+1);
• } until (false);
• }

Algorithm NextValue (k)

// x [1] , . . . . x [k-1] have been assigned integer values in the range [1, m] such that
// adjacent vertices have distinct integers. A value for x [k] is determined in the range
// [0, m].x[k] is assigned the next highest numbered color while maintaining distinctness
// from the adjacent vertices of vertex k. If no such color exists, then x [k] is 0.
{
repeat
{
x [k]: = (x [k] +1) mod (m+1) // Next highest color.
If (x [k] = 0) then return; // All colors have been used for j := 1 to n do
{ // check if this color is distinct from adjacent colors if ((G [k, j] 0) and (x [k] = x
[j]))
// If (k, j) is and edge and if adj. vertices have the same color. then break;
}
if (j = n+1) then return; // New color found
} until (false); // Otherwise try to find another color.
}

326|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

1.10 HAMILTONIAN CYCLES

• Let G = (V, E) be a connected graph with n vertices. A Hamiltonian cycle


(suggested by William Hamilton) is a round-trip path along n edges of G that visits
every vertex once and returns to its starting position.

• In other vertices of G are visited in the order v1, v2, . .

• . . . , vn+1, then the edges (vi, vi+1) are in E, 1 < i < n, and the vi are distinct expect
for v1 and vn+1, which are equal.

• The graph G1 contains the Hamiltonian cycle 1, 2, 8, 7, 6, 5, 4, 3, 1. The graph G2


contains no Hamiltonian cycle.

327|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
• The backtracking solution vector (x1, . . . . . xn) is defined so that xi represents the ith
visited vertex of the proposed cycle. If k = 1, then x1 can be any of the n vertices.
• To avoid printing the same cycle n times, we require that x1 = 1. If 1 < k < n, then xk
can be any vertex v that is distinct from x1, x2, . . . , xk–1 and v is connected by an
edge to kx-1. The vertex xn can only be one remaining vertex and it must be
connected to both xn-1 and x1.
• Using Next Value algorithm we can recursive particularize the backtracking schema
to find all Hamiltonina cycles.This algorithm is started by first initializing the
adjacency matrix G 1[1:n,1:n], then setting x[2:n] to zero and x[1] to 1, and then
executing Hamiltonian (2).
The traveling salesperson problem using dynamic programming asked for a tour that
has minimum cost. This tour is a Hamiltonian cycles. For the simple case of a graph all of
whose edge costs are identical, Hamiltonian will find a minimum-cost tour if a tour exists.

Algorithm NextValue (k)

// x [1: k-1] is a path of k – 1 distinct vertices . If x[k] = 0, then no vertex has as yet been
// assigned to x [k]. After execution, x[k] is assigned to the next highest numbered vertex
// which does not already appear in x [1 : k – 1] and is connected by an edge to x [k –
1].
// Otherwise x [k] = 0. If k = n, then in addition x [k] is connected to x [1].
{
repeat
{
x [k] := (x [k] +1) mod (n+1); // Next vertex. If (x [k] = 0) then return;
If (G [x [k – 1], x [k]] 0) then
{ // Is there an edge?
for j := 1 to k – 1 do if (x [j] = x [k]) then break;
// check for distinctness.
If (j = k) then // If true, then the vertex is distinct. If ((k < n) or ((k = n) and G [x [n], x [1]]
0))
then return;
}
} until (false);
}
{ // Is there an edge?
for j := 1 to k – 1 do if (x [j] = x [k]) then break;
// check for distinctness.
If (j = k) then // If true, then the vertex is distinct. If ((k < n) or ((k = n) and G [x [n], x [1]]
0))
then return;
}
328|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
} until (false);
}

Algorithm Hamiltonian (k)


// This algorithm uses the recursive formulation of backtracking to find all the
Hamiltonian
// cycles of a graph. The graph is stored as an adjacency matrix G [1: n, 1: n]. All cycles
begin
// at node 1.
{
repeat
{ // Generate values for x [k].
NextValue (k); //Assign a legal Next value to x [k]. if (x [k] = 0) then return;
if (k = n) then write (x [1: n]); else Hamiltonian (k + 1)
} until (false);
}
1.11 KNAPSACK PROBLEM USING BACKTRACKING
• The problem is similar to the zero-one (0/1) knapsack optimization
problem is dynamic programming algorithm.
• We are given ‘n’ positive weights Wi and ’n’ positive profits Pi, and a
positive number ‘m’ that is the knapsack capacity, the is problem calls
for choosing a subset of the weights such that,

WiXi m and PiXi is Maximized


1 i n
Xi Constitute Zero-one valued Vector.
The Solution space is the same as that for the sum of subset’s problem.
Bounding functions are needed to help kill some live nodes without expanding
them. A good bounding function for this problem is obtained by using an upper
bound on the value of the best feasible solution obtainable by expanding the
given live node.
The profits and weights are assigned in descending order depend upon the ratio.

(i.e.) Pi/Wi P(I+1) / W(I+1)

Solution
After assigning the profit and weights ,we have to take the first object weights
and check if the first weight is less than or equal to the capacity, if so then we
include that object (i.e.) the unit is 1.(i.e.) K 1.
Then We are going to the next object, if the object weight is exceeded that
object does not fit. So unit of that object is ‘0’.(i.e.) K=0.

329|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
Then We are going to the bounding function ,this function determines an upper
bound on the best solution obtainable at level K+1.
Repeat the process until we reach the optimal solution.
Algorithm Bknap(k,cp,cw

// ‘m’ is the size of the knapsack; ‘n’ no.of weights & profits. W[]&P[] are the
//weights & weights. P[I]/W[I] P[I+1]/W[I+1].

//fw Final weights of knapsack.

//fp final max.profit.

//x[k] = 0 if W[k] is not the knapsack,else X[k]=1.


{

// Generate left child. If((W+W[k]

m) then

Y[k] =1;

If(k<n) then Bnap(k+1,cp+P[k],Cw +W[k]) If((Cp + p[w] > fp)

and (k=n)) then

fp = cp + P[k]; fw = Cw+W[k];

for j=1 to k do X[j] = Y[j];

if(Bound(cp,cw,k) fp) then

y[k] = 0;

if(k<n) then Bnap (K+1,cp,cw); if((cp>fp)

and (k=n)) then

fp = cp; fw = cw;

for j=1 to k do X[j] = Y[j];

}
330|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
}
}

9.Practice Quiz

1. In a binary tree, the number of terminal nodes (leaf nodes)are 10, then the number of
nodes with two children are

a)9

b)10

c)11

d)20

2. If the post order and preorder traversal of a binary tree are M,N,L,P,R,O,K and
M,N,L,P,R,O,K respectively then, the in order traversal of that tree is

a) M,L,N,K,P,O,R

b)L,N,M,K,P,R,O

c)P,R,O,K,L,N,M

d)M,N,O,P,R,L,K

3. Which of the following statement is true in case of a binary tree

a) There is no node with degree greater than two


b) The left or right subtree can not be empty
c) A node is said to be a leaf only if it contains one child
d) the level of any node is two more than the level of parent node

4. When comparing the binary tree with the general tree, which statement is true?

a) The binary tree as well as the general tree can be empty


b) The binary tree or the general tree can never be empty
c) The general tree, like the binary tree consists of left and right child
d) Binary tree consists of left and right child, whereas a general tree consists of collection
of sub trees.
5. If T(n,e) represents the maximum time taken by DFS for an n-vertex, e-edge graph, then
what is the value of T(n,e) if adjacency lists are used.

a) O(n+e)

b) O(ne)

c) O(n-e)

331|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
d) O(2n )

6. If S(n,e) represents the maximum additional space taken by DFS for an n-vertex, e-edge
graph, then what is the value of S(n,e) if adjacency lists are used.

a) O(n)

b) O(n+e)

c) O(n-e)

d) O(2n )
7. If T(n,e) represents the time complexity of DFS for an n-vertex, e-edge graph, then what
is the value of T(n,e) if adjacency matrix is used.
a) O(n+e)
b) O(ne)
c) O(1)
d) O(n2)
8. If adjacency matrix is used, then what is the time complexity of BFS algorithm?
a) O(n)
b) O(e)
c) O(n2)
d) O(n+e)

9. The broken edges of the depth first spanning tree of the graph are called _ _ _

a) it contains no articulation points

b) it contains no loops
c) it contains no cycle

d) it contains no parallel edges

10. A graph G is biconnected if and only if _ _ _ _ _ _ _ _ _

a) it contains no articulation points

b) it contains no loops
c) it contains no cycle
d) it contains no parallel edges

10. Assignments

332|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
S.No Question BL CO
1 Explain Hamiltonian cycles with example? 2 1
2 Explain 8-queens problem? 2 1
3 Explain sum of subset problem? 2 1
4 Describe Graph colouring method? 2 1
5 Discuss Knapsack problem? 3 1
6 Describe General method with examples? 3 1

11. Part A- Question & Answers

S.No Question& Answers BL CO


1 Define finish time
Ans:The finish time fi (S) of job i is the time at which all tasks of job i have
been completed in schedule S.The finish time F(S) of schedule S is given by 1 1
F(S)=max{f(S)}1<i<n

2 2.Define mean flow


time
Ans: The mean flow time MFT (S) is
defined to be] Σfi(S)MFT (S) = 1 n
1 1
1<i<n

3 Define optimal finish time.


Ans: Optimal finish time scheduling for a given set of tasks is a
nonpreemptive schedule S for which F (S) is minimum over all 1 1
nonpreemptive schedules S.

4 Define preemptive optimal finish time.


Ans:Preemptive optimal finish time scheduling for a given set of tasks is a
1 1
preemptive schedule S for which F (S) is minimum over all preemptive
schedules S.
5 What are the requirements that are needed for performing Backtracking?
Ans:To solve any problem using backtracking, it requires that all the
solutions satisfy a complex set of constraints. They are:
i. Explicit constraints. 1 1
ii. Implicit
constraints.

12. Part B- Questions

S.No Question BL CO
1 Write an algorithm to estimate the efficiency of backtracking? 1 1

2 Explain 4-queen problem using backtracking? 2 1

333|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

3 Explain spanning trees and minimum cost spanning trees with 2 1


suitable example?

4 Explain about graph coloring and Hamiltonian cycles with 3 1


examples?

5 Explain about techniques for binary trees and techniques for 3 1


graphs?

13. Supportive Online Certification Courses


1. Design analysis of algorithms recursive algorithms NPTEL MOOOC -4 weeks course by
Prof.Madhavan mukund
14. Real Time Applications
S.No Application CO
1 Social Networking Websites: In social networks, we can find people within 1
a given distance ‗k‘ from a person using Breadth First Search till ‗k‘ levels.
2 Graphs are good in modelling real world problems like representing cities 1
which are connected by roads and finding the paths between cities,
modelling air traffic controller system, etc. Based on the traversal,
different complexities arise.
3 A large number of graph operations are present, such as Bellman ford 1
minimum spanning tree, breadth-first search, shortest path etc., having
applications in different problem domains like data mining, and network
analysis, route finding, game theory.
4 GPS Navigation systems: Breadth First Search is used to find all 1
neighbouring locations.
5 Broadcasting in Network: In networks, a broadcasted packet follows 1
Breadth First Search to reach all nodes.

15. Contents Beyond the Syllabus

1. Isomorphic Graphs

Two graphs G1 and G2 are said to be isomorphic if −


• Their number of components (vertices and edges) is same.
• Their edge connectivity is retained.
2. Cocktail Sort

Cocktail sort is the variation of Bubble Sort which traverses the list in both directions
alternatively. It is different from bubble sort in the sense that, bubble sort traverses the list in
forward direction only, while this algorithm traverses in forward as well as backward
direction in one iteration.

16. Prescribed Text Books & Reference Books


334|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2
SVCE KADAPA

`
Text Book
1. Introduction to Design Analysis of Algorithms - K. Raghava Rao 2nd Edition
References:
1. Design And Analysis Of Algorithms-A.Puntambekar Technical Publications 2010.
17. Mini Project Suggestion
1.Chromatic polynomial
The chromatic polynomial is a graph polynomial studied in algebraic graph theory, a
branch of mathematics. It counts the number of graph colorings as a function of the
number of colors and was originally defined by George David Birkhoff to study the four
color problem.
2. A Harmonious Coloring
It is a recent growing topic in the last three decades. Harmonious colouring number is
used in the different families of graph such as trees, cycles, complete bipartite graphs etc.
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 re-computing formula values in spreadsheets,
logic synthesis, determining the order of compilation tasks to perform in make files, data
serialization, and resolving symbol dependencies in linkers.

335|D A A - U N I T - I I I
B.TECH_CSE_SEM 3 2

You might also like