Mcs 211 Complete Pcti
Mcs 211 Complete Pcti
Block-1 Unit-1
Basics of an Algorithm and Its Properties
Topics to be Covered
Introduction
Example of an Algorithm
Types of Problems
• Let us find the GCD of a = 1071 and b = 462 using Euclid‟s algorithm :-
• Divide a=1071 by b=462 and store the remainder in r. r= 1071 % 462
(here, % represents the remainder operator). R =147
• If r = 0, the algorithm terminates and b is the GCD. Otherwise, go to
Step 3. Here, r is not zero, so we will go to Step 3.
• The integer will get the current value of integer b and the new value
of integer b will be the current value of r. Here, a=462 and b=147
• Go back to Step 1.
• Selection/Decision
• Iteration/Repetition or Loop
• Procedure
• Recursion
+91 - 9319133134 , [email protected]
A Survey of Common Running Time
• To compare two algorithms for a problem, running time is generally used
which is defined as the time taken by an algorithm in generating the output.
• An algorithm is better if it takes less running time. The “time” here is not
necessarily the clock time. However, this measure should be invariant to any
hardware used.
• The running time of an algorithm can be represented in terms of the number
of operations executed for a given input. More the number of operations, the
larger the running time of an algorithm.
• This running time of an algorithm for producing the output is also known as
time complexity.
Exponential Time:
Beyond the
polynomial time • Exponential Time O(2n)
complexity there are • Factorial Time O(n!)
other two types of
bounds :
Sorting
Searching
Graph problems
Combinatorial problems
Geometric problems
Numerical problems
+91 - 9319133134 , [email protected]
Types of Problems
Sorting
• The sorting is the process to arrange the given set of items in
a certain
• order, assuming that the nature of the items allow such an
ordering. For example, sorting a set of numbers in
increasing or decreasing order and sorting the character
strings, like names, in an alphabetical order. For any sorting
algorithm following two characteristics are desirable:
• Stability
• In-place
+91 - 9319133134 , [email protected]
Types of Problems
Searching
• Searching is finding an element, referred as search key, in a
given set of items. Searching is one of the most important
and frequently performed operation on any
dataset/database.
Graph Problems
• It is helpful for researchers to map a computational
problem to a graph problem. Many computational
problems can be solved using graph.
• Most of the problems like: visiting all the nodes of a
graph, routing in networks , finding the minimum cost
path, i.e.
• The shortest path, path with minimum delay etc. Can be
solved efficiently with graph algorithms.
+91 - 9319133134 , [email protected]
Types of Problems
Combinatorial Problems
Geometric Problems
• These types of problems have a combination of solutions
i.e. more than one solution are possible.
• The aim of the combinatorial problems is to find
permutations, combinations, or subsets, satisfying the
given conditions.
• Numerical Problems
• Problems of numerical computing nature are simultaneous linear
equations ,differential equations, definite integration, and statistics.
Most of the numerical problems could be solved approximately.
• The biggest drawback of numerical algorithms is the accumulation of
errors over the multiple iterations, due to rounding off the approximated
result at each iteration.
• Step 1. Divide the problem (top level) into a set of sub-problems (lower
level).
• Greedy Technique
• Using Greedy approach, optimization problems are solved efficiently.
• In an optimization problem, the given set of input values are either to
be maximized or minimized, subject to some constraints or conditions.
• Greedy algorithm always picks the best choice (greedy approach) out
of many at a particular moment to optimize a given objective
• Knapsack Problem
+91 - 9319133134 , [email protected]
Problem Solving Techniques
Dynamic Programming
• Dynamic Programming approach is a bottom-up approach
which involves finding solution of all sub-problems, saving
these partial results, and then reusing them to solve larger
sub-problems until the solution to the original problem is
obtained.
• Randomized Algorithms
• In a randomized algorithm, a random number is selected at any stage of
the solution and is used for computation of the solution, that‟s why it is
called as randomized algorithm.
• In other words it can be said that algorithms that make random choices
for faster solutions are known as randomized algorithms.
Problem Solving Techniques
• Backtracking Algorithm
• Backtracking algorithm is like creating checkpoints while exploring
new solutions. It works analogues to depth-first search. It searches all
the possible solutions.
• N = {1, 2, 3, …}
• I = {…, ─ 2, ─, 0, 1, 2, ….}
• R = set of Real numbers.
• For two given sets A and B a rule f which associates with each element
of A, a unique element of B, is called a function from A to B. If f is a
function from a set A to a set B then we denote the fact by f: A ->B. For
example the function f which associates the cube of a real number with a
given real number x, can be written as 𝑓(𝑥) = x3.
• Definition
• b mod n: if n is a given positive integer and b is any integer, then
b mod n=r where0 r <n and b = k * n +r
+91 - 9319133134, [email protected]
Mathematical Expectation
• Assuming that marks within a class are uniformly scored by the students in
the class, the above table may be approximated by the following more
concise table:
T (n) = n*log2(n)
• Asymptotic Notations
• Big-O notation,
3n2 + 4n – 2 = O(n2).
+91 - 9319133134, [email protected]
Asymptotic Analysis & Notations
• f(n) = 𝗇(g(n)) if and only if there exists some constants C and 𝑛0 such
that f(n) ³C.g(n) :" n ≥ 𝑛0 . The following graph illustrates the growth of
f(n) = 𝗇(g(n))
+91 - 9319133134, [email protected]
Asymptotic Analysis & Notations
provided.
𝒇 𝒏 = 𝗇 (𝒈 𝒏 )
• Theorem: For any two functions f(x) and g(x), f(x) = O (g(x)) if and
only if f(x) = O (g(x)) and f(x) = (g(x)).
• An algorithm takes some sort of input and produces some sort of output
• Introduction
• Important Topics
• Summary
+91 - 9319133134 , [email protected]
Introduction
𝑖𝑛𝑡 𝑥;
𝑥=𝑥+5
𝑥=𝑥−5
for (i = 1; i<= n; i += c) {
// simple statement(s) }
for (int i = n; i> 0; i -= c) {
// simple statement(s)
}
+91 - 9319133134 , [email protected]
Analysis of Simple Constructs or
Constant Time
• O(nc): This is a running time of nested loops. Time complexity of nested
loops is equal to the number of times the innermost statements is executed.
For example, the following sample loops have O(n2) time complexity.
Example –
for (int i = 1; i<=n; i += c) {
• A Summation Algorithm
• The following is a simple program to calculate
int sum of n cube (int n)
{
int i, temp result;
Temp result =0;
for (i=1 ; I <=n; i++)
Temp result = temp result + i * i * i
return tempresult;
}
+91 - 9319133134 , [email protected]
Analysis of Simple Algorithms
• Polynomial Evaluation
• A polynomial is an expression that contains more than two terms. A
term comprises of a coefficient and an exponent.
P(x) = 15x4+7x2+9x+7 P(x)=14x4+17x3−12x2+13x+16
• A polynomial may be represented in form of array or structure.
};
+91 - 9319133134 , [email protected]
Analysis of Simple Algorithms
• Analysis of Brute Force Method
• A brute force approach to evaluate a polynomial is to evaluate all
terms one by one.
• First calculate xn, multiply the value with the related coefficient 𝑎n,
repeat the same steps for other terms ,then return the sum
p(x)= an∗x∗x∗ …∗x∗x +an−1∗x∗x∗ … ∗x∗x +an−2∗x∗x∗
…∗x∗x +⋯+a2∗x∗x∗+a1∗x+a0
P(x)=(…(((an∗x+an−1)∗x+an−2)∗x+...+a2)∗x+a1)∗x+a0
Evaluate_Horner (a,n,x)
{
p = A[n];
for (i = n-1; i≤0;i--)
p = p * x + A[i];
return p;
}
• Complexity Analysis
• Polynomial of degree n using Horner‟s rule is evaluated as below:
• Initial assignment, p = a[n]
• After the first iteration p = xan +an–1
• After the second iteration, p = x(xan + an–1) + an–2
• Every subsequent iteration uses the result of previous iteration i.e next
iteration multiplies the previous value of p then adds the next
coefficient.
• Matrix is very important tool which is managing the data in matrix form it
will be easy to manipulate and obtain more information. One of the basic
operations on matrices is multiplication.
• For Example multiply two square matrix of order n x n and find its time
complexity.
• Multiply two matrices A and B of order n*n each and store the result in
matrix C of order n*n.A square matrix of order n*n is an arrangement of
set of elements in n rows and n columns.
• Step I :
• Pseudo code: For Matrix multiplication problem where we will
multiply two matrices A and B of order 3x3 each and store the
result in matrix C of order 3x3.
• Multiply first row first element of first matrix with first column first
element of second matrix.
• Complexity Analysis
• First step is, for loop that will be executed n number of times i.e. it
will take O(n) time.
• The second nested for loop will also run for n number of time and will
take O(n) time & constant time i.e. O(1) .
• Linear_ Search( A[ ], X)
• Step 1: Initialize i to 1
• Step 2: if i exceeds the end of an array then print “element not
found” and Exit
• Step 3: if A[i] = X then Print “Element X Found at index i in the
array” and Exit
• Step 4: Increment i and go to Step 2
• This algorithm is not recommended for use for a bigger size array .
• Largest element in the given unsorted array, bubbles up towards the
last place in every cycle/pass .
• Introduction
• Recurrence Relation
• Methods for Solving Recurrence Relation
• Important Topics
• Summary
+91-9319133134, [email protected]
Introduction
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Substitution Method
• Substitution is opposite of induction .We start at n and move
backward. A substitution method is one, in which we guess a bound
and then use mathematical induction to prove whether our guess is
correct or not. It comprises two steps:
• Step1: Guess the asymptotic bound of the Solution.
• Step2: Prove the correctness of the guess using
Mathematical Induction
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Example :- A Fibonacci sequence 𝑓0, 𝑓1, 𝑓2, … .. can be defined by the
recurrence relation as:
• (Basic Step)The given recurrence says that if n=0 then 𝑓0 = 0 and if n=1 then 𝑓1
= 1 . These two conditions (or values) where recursion does not call itself is
called an initial condition (or Base conditions).
• (Recursive step): This step is used to find new terms 𝑓2, 𝑓3, … . ., from the
existing (preceding) terms, by using the formula 𝑓𝑛 = 𝑓𝑛−1 + 𝑓𝑛−2 for 𝑛 ≥ 2.
• This formula says that “by adding two previous sequence (or term) we can get the
next term”.
• For example 𝒇𝟐 = 𝒇𝟏 + 𝒇𝟎 = 𝟏 + 𝟎 = 𝟏;
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
+91 - 9319137138 ,
[email protected]
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Recursion Tree method
• Recursion tree method is especially used to solve a recurrence of the form:
https://www.gatevidyalay.com/recursion-tree-
solving-recurrence-relations/#google_vignette
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
+91 - 9319137138 ,
[email protected]
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Method (steps) for solving a recurrence
(𝒏) = 𝑻 (𝒏/𝒃) + (𝒏) using recursion
tree.
• We make a recursion tree for a
given recurrence as follows:
• To make a recursion tree of a
given recurrence (1), First put the
value of 𝒇(𝒏) at root node of a
tree and make a number of
child nodes of this root value 𝒇(𝒏)
Now tree will be looks like as:
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Now we have to find the value of 𝑻 (𝒏) by putting (n/b) in place of
n in 𝒃equation .That is
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Master Method
• A function f(n) is asymptotically positive if any only if there exists
a real number n such that f(x) > 0 for all x > n.
• The master method provides us a straight forward method for solving
recurrences of the form𝑻(𝒏) = 𝒂𝑻 𝒏 𝒃+ (𝒏), where a > 1 and b > 1 are
constants and f(n) is Asymptotically positive function. This
recurrence gives us the running time of an algorithm that divides a
problem of size n into a sub problems of size The a sub problems are
solved recursively, each in time T(𝒏)/𝒃.
+91-9319133134, [email protected]
Methods for Solving Recurrence
Relations
• Theorem1: Master Theorem
• The Master Method requires memorization of the following 3 cases;
then the solution of many recurrences can be determined quite easily,
often without using pencil & paper.
+91-9319133134, [email protected]
Important Topics
+91-9319133134, [email protected]
Summary
+91-9319133134, [email protected]
+91-9319133134, [email protected]
Design and Analysis of Algorithms
Block-2 Unit-1
Greedy Techniques
Topics to be Covered
• Introduction
• Example to Understand Greedy Techniques
• Formalization of Greedy Techniques
• An overview of Local and Global Optima
• Fractional Knapsack Problem
• A Task Scheduling Algorithm
• Huffman Codes
• Important Topics
• Summary
+91 - 9319133134, [email protected]
Introduction
• In between ‘A’ and ‘B’, there are four gas stations, G1, G2, G3, and
G4, which are at distance of 20 KM, 37.5 KM, 55 KM, and 75 KM,
from location ‘A’ respectively. The problem is to determine the
minimum number of refills needed to reach the location ‘B’ from
location ‘A’.
+91 - 9319133134, [email protected]
Examples to Understand Greedy
Techniques
• Solution: Suppose, the tank refill decision criteria is considered to refill at
the gas station which is nearest when the tank is about to get empty.
• According to the criteria, if we start from location ‘A’, the tank will be
refilled at the second gas station (G2) as it is 37.5 KM from ‘A’.
• After this, we need to refill at the fourth gas station (G4) which is at a
distance of 37.5 KM from G2.
• From G4, we can easily reach the location ‘B’ as it is 20 KM. Therefore,
the number of refills required is two as represented in the Figure.
• For a given problem with ‘n’ input values, the greedy approach will
decide criteria to select values, termed as selection criteria, and will run
for ‘n’ times. In each run, following steps will be performed:
• It will perform selection based upon the selection criteria. This
returns a value from the considered input values and also removes
the selected value from the input values.
• It will check the feasibility of the selected value.
• If the solution is feasible then the selected value is added to the
solution set else step 1 is repeated.
https://www.geeksforg
eeks.org/fractional-
+91 - 9319133134, [email protected] knapsack-problem/
Fractional Knapsack Problem
• Now, greedy approach has to select the set of three tasks and schedule
them in such a way that the total profit is maximum on their
completion.
https://towardsdatascience.com/h
uffman-encoding-python-
implementation-8448c3654328 +91 - 9319133134, [email protected]
Huffman Codes
https://towardsdatascience.com/h
uffman-encoding-python-
implementation-8448c3654328 +91 - 9319133134, [email protected]
Huffman Codes
https://towardsdatascience.com/huffman-encoding-python-
implementation-8448c3654328
• Local optimal solutions correspond to the set of all the feasible solutions
that are best locally for an optimization problem. Global optimal
solution corresponds to the best solution of the optimization problem.
• Introduction
• Recurrence Relation Formulation in Divide and Conquer Technique
• Binary Search Algorithm
• Sorting Algorithms
• Integer Multiplication
• Matrix Multiplication Algorithm
• Important Topics
• Summary
+91-9319133134, [email protected]
Introduction
+91-9319133134, [email protected]
Recurrence Relations Formulations in
Divide and Conquer Approach
• Divide and Conquer approach the running time is equated as a
recurrence relation which is based upon three steps:
• Divide: Dividing the given problem into sub-problems in such a way that
each sub-problem is equivalent to the original problem but its size is
smaller than the original one. Further sub-division of each sub-problem is
done till either it is directly solvable or it is impossible to perform sub-
division which indicates that there is a direct solution of the sub-problem.
• Conquer: Each sub-problem solves itself by calling itself recursively.
• Combine: Each solution of the sub-problem is combined to obtain the
original solution.
+91-9319133134, [email protected]
Recurrence Relations Formulations in
Divide and Conquer Approach
• where,
+91-9319133134, [email protected]
Recurrence Relations Formulations in
Divide and Conquer Approach
• f(n) − D(n) + C(n) − time required to divide the problem and combine
the solutions respectively. If the problem size is small enough say , n ≤
C for some constant C , we have a best case which can be directly
solved in a constant time: θ(1), otherwise, divide a problem of a size n
into sub problems, each of 1/b size.
Solution of
Sub-problem
sub-problem
Solution of
Problem
Problem
Solution of
Sub-problem
sub-problem
+91-9319133134, [email protected]
Binary Search
+91-9319133134, [email protected]
Binary Search
+91-9319133134, [email protected]
Binary Search
+91-9319133134, [email protected]
Binary Search
• Where, a, b, and f(n) are replaced with values 1, 2, k (constant less than
n), respectively. K is constant value for divide and conquer operation on
solving this recurrence relation by substitution method, the computational
complexity for binary search is O(logn).
+91-9319133134, [email protected]
Sorting Algorithms
+91-9319133134, [email protected]
Sorting Algorithms
• Merge-Sort
• Merge-Sort algorithm is a divide-and-conquer based sorting
algorithm. It follows a divide and conquer approach to perform
sorting. The algorithm in divide step repeatedly partitions an array
into several sub arrays until each sub array consists of a single
element.
+91-9319133134, [email protected]
Sorting Algorithms
+91-9319133134, [email protected]
Sorting Algorithms
+91-9319133134, [email protected]
Sorting Algorithms
• Quick-Sort
Quick-Sort is another sorting algorithm that works on the principle of
divide- and-conquer approach. It works by arranging the elements in an
array by identifying their correct place (or index).
+91-9319133134, [email protected]
Sorting Algorithms
+91-9319133134, [email protected]
Sorting Algorithms
+91-9319133134, [email protected]
Sorting Algorithms
• Analysis of Quick-Sort:
• The computation complexity of Quick-Sort is based on the
arrangement of array elements. Arrangement of elements effects
the partitioning of an array. If partitioning is unbalanced,
partitioning procedure will perform more number of times in
comparison to balanced partition. Therefore, the Quick-Sort
has different complexity in different scenarios:
• Best Case: If the input data is not sorted, then the partitioning of
subarray is balanced. (i.e. 0(nlogn))
+91-9319133134, [email protected]
Sorting Algorithms
• Worst Case: If the given input array is already sorted or almost sorted, then
the partitioning of the subarray is unbalancing in this case the algorithm runs
asymptotically as slow as Insertion sort(i.e. 0(n2)).
• Average Case: Except best case or worst case. The shows the recursion
depth of Quick-sort for Best, Worst and Average cases.
+91-9319133134, [email protected]
Integer Multiplication
• The brute force algorithm for multiplying two large integer numbers which
everyone of us uses by hand, takes quadratic time i.e., O (n2). Because each
digit of one number is multiplied by each digit in another number.
• Assume X and Y are two n digits number. Divide X and Y into two halves of
approximately n/2 digits each.
• The following examples illustrate the division process:
• 657,138= 657* 103 + 138
• 6578,381 = 6578* 103 +381
+91-9319133134, [email protected]
Integer Multiplication
• Let us generalize the number representation. If Z is an n-digit
number, it would be divided, into two halves , the first half with
Ceiling with[n/2] and the second half with Floor[ n/2] as shown
below:
• Z( n digit number) = 𝑋L * 10m + 𝑋R
• Suppose are given two n- digit numbers:
• Z1 = 𝑋L * 10m + 𝑋R
• Z2 = 𝑌L * 10m + 𝑌R
• Z1 * Z2 = (𝑋L * 10m+ 𝑋R)(𝑌L * 10m + 𝑌R
• = 𝑋L ∗ 𝑌L * 102m + (𝑋L ∗ 𝑌R+ 𝑌L ∗ 𝑋R) 10m + 𝑋R𝑌R
+91-9319133134, [email protected]
Matrix Multiplication
• Matrix multiplication a binary operation of multiplying two or
more matrices one by one that are conformable for
multiplication. For example two matrices A, B having the
dimensions of 𝑝 × 𝑞 and 𝑠 × 𝑡 respectively; would be
conformable for 𝐴 × 𝐵 multiplication only if q==s and for 𝐵 × 𝐴
multiplication only if t==p.
• Matrix multiplication is associative in the sense that if A, B, and
C are three matrices of order 𝑚 × 𝑛, 𝑛 × 𝑝 and 𝑝 × 𝑞 then the
matrices (AB)C and A(BC) are defined as (AB)C = A (BC) and
the product is an 𝑚 × 𝑞 matrix.
+91-9319133134, [email protected]
Matrix Multiplication
• Matrix multiplication is not commutative. For example two
matrices A and B having dimensions 𝑚 × 𝑛 and 𝑛 × 𝑝 then the
matrix AB = BA can’t be defined. Because BA is not
conformable for multiplication, even if AB are conformable for
matrix multiplication.
• For three or more matrices, matrix multiplication is associative,
yet the number of scalar multiplications may vary significantly
depending upon how we pair the matrices and their product
matrices to get the final product.
+91-9319133134, [email protected]
Matrix Multiplication
+91-9319133134, [email protected]
Matrix Multiplication
+91-9319133134, [email protected]
Matrix Multiplication
+91-9319133134, [email protected]
Matrix Multiplication
+91-9319133134, [email protected]
Matrix Multiplication
• Strassen’s Matrix Multiplication Algorithm
Strassen’s algorithm makes use of the same divide and conquer approach
• Divide the input matrices A and B into n/2 x n/2 sub-matrices, which
takes Θ(1) time.
• Now calculate the 7 sub-matrices M1-M7 by using below formulas:
M1=(A11+A22)(B11+B22)
M2= (A21+A22) B11
M3= A11 (B12−B22) M4= A22 (B21−B−11)
M5= (A11+A12) B22
M6= (A21−A11) (B11+B12)
M7= (A12−A22) (B21+B22)
+91-9319133134, [email protected]
Matrix Multiplication
• To get the desired sub-matrices C11, C12, C21, and C22 of the
result matrix C by adding and subtracting various
combinations of the Mi sub-matrices. These four sub-
matrices in Θ(n2)time.
C11= M1+M4−M5+M7 C12= M3+M5
C21= M2+M4
C22= M1−M2+M3+M6
+91-9319133134, [email protected]
Important Topics
+91-9319133134, [email protected]
Summary
• In this session we have seen that Divide and Conquer approach
follows a recursive approach which making a recursive call to
itself until a base (or boundary) condition of a problem is not
reached but with reduced problem size.
• Divide and Conquer is a top-down approach, which consists of
three steps:
• Divide: the given problem is break down into smaller parts.
• Conquer: Solve each sub-problem by recursively calling them.
• Combine: each sub-solution is combined to generate solution
to the original problem.
+91-9319133134, [email protected]
+91-9319133134, [email protected]
Design and Analysis of Algorithms
Block-2 Unit-3
Graph Algorithms-I
Topics to be Covered
• Introduction
• Basic definition and Terminologies
• Graph Representation Schemes
• Graph Traversal Schemes
• Directed Acyclic Graph and Topological Ordering
• Strongly Connected Components
• Important Topics
• Summary
+91-9319133134, [email protected]
Introduction
• Graphs are most widely used mathematical structure. It is
widely used in finding shortest path routes, shortest path
between every pair of vertices, in computing maximum flow
problem which has applications in a large range of problems
related to airlines scheduling, maximum bipartite matching
and image segmentation.
• A graph can be used to model a social network which
comprises millions of users or interest groups which can be
represented as nodes.
+91-9319133134, [email protected]
Basic Definition and Terminologies
+91-9319133134, [email protected]
Basic Definition and Terminologies
• Graph Types:
+91-9319133134, [email protected]
Basic Definition and Terminologies
• Graph Types:
+91-9319133134, [email protected]
Basic Definition and Terminologies
• Undirected Graph:
• A graph in which the edges do not
have any direction and all the edges
are in bi-direction.
• In undirected graph if there is an
edge from u to v then we can move
from node u to node v and as well
as from node v to node u.
Undirected Graph
+91-9319133134, [email protected]
Basic Definition and Terminologies
• Directed Graph: A graph in
which the edges have direction. It
is also called digraph.
• This is usually indicated with an
arrow on the edge.
• In a directed graph if there is an
edge from u to v then we can
move from a node u to a node v
only
Directed graph
Basic Definition and Terminologies
• Subgraph:
• A Subgraph of G is a graph G’ such that V(G’)
⊆ V(G) and E(G’) ⊆ E(G)i.e., a graph whose
vertices and edges are subsets of another graph. It is
not necessary that a Subgraph will have all the edges
of graph or all the nodes. This is a Subgraph of the
graph which has the nodes A, B, C, D. In this there
are C, B, D nodes.
+91-9319133134, [email protected]
Basic Definition and Terminologies
• Connected Graph:
• An undirected graph is said to be connected if for every pair of two
different vertices 𝑣i , 𝑣j , there is a path between these two vertices.
The graph 𝐺1 is connected whereas 𝐺2 is not connected.
+91-9319133134, [email protected]
Graph Representation
+91-9319133134, [email protected]
Graph Representation
• Adjacency Matrix:
• The adjacency matrix of a graph with V vertices is V x V Boolean
matrix with one row and one column for each of the graph’s vertices
Adjacency matrix representation is typically used to represent both
directed and undirected graphs.
+91-9319133134, [email protected]
Graph Representation
• Adjacency matrix representation of a graph given in
above figure
+91-9319133134, [email protected]
Graph Representation
• Adjacency List
• Adjacency list representation is typically used to represent graphs,
where the number edges |E| is much less than |V|2.Adjacency list is
represented as an array of |V| linked lists. There is one linked list for
every vertex node in a graph ί each node in this linked list is a reference
to the other vertices which share an edge with the current vertex.
+91-9319133134, [email protected]
Graph Representation
+91-9319133134, [email protected]
Graph Traversal Algorithms
• Traversal algorithms are used to navigate across a given graph among all
the nodes using all possible vertices. These algorithms will help us in
finding the nodes, making paths that are shortest or feasible or prioritized
in nature.
• There are two key graphs traversal
• Depth First Search(DFS)
• Breadth First Search (BFS) algorithms.
+91-9319133134, [email protected]
Graph Traversal Algorithms
+91-9319133134, [email protected]
Graph Traversal Algorithms
• Depth First Search(DFS) : As the name says Depth, we will return the elements
of a tree or a graph in depth wise order. Let us understand from an example.
+91-9319133134, [email protected]
Graph Traversal Algorithms
• Breadth First Search (BFS) : According to the BFS, you must traverse the
graph in a breadthwise direction:
•To begin, move horizontally and visit all the current layer's nodes.
•Continue to the next layer.
https://www.simplilearn.co
+91-9319133134, [email protected] m/tutorials/data-structure-
tutorial/bfs-algorithm
Graph Traversal Algorithms
• Complexities:
• Time complexity: O (V + E),where 𝑂(𝑉) is a total time taken to
complete queue operations (insertion and deletion of vertices.
Insertion and deletion of a single vertex takes O(1) unit of time .
• Since there are V number of vertices in the graph, it will take
O(V) time. The time taken to traverse each adjacency list only
once is O(E). Therefore, the total time is O (V + E).
+91-9319133134, [email protected]
Directed Acyclic Graph and Topological
Ordering
• A directed graph without a cycle is called a directed acyclic graph (or a
(DAG (for short) which is a frequently used graph structure to represent
precedence relation or dependence is a network. The following is a
example of a directed acyclic task graph.
+91-9319133134, [email protected]
Directed Acyclic Graph and Topological
Ordering
• In this graph except vertex V1, all other vertices are dependent
upon other vertices.
• Any major task can be broken down into several subtasks. The
successful completion of the task is possible only when all the
subtasks are completed successfully.
+91-9319133134, [email protected]
Directed Acyclic Graph and Topological
Ordering
• Function topological sort(G)
Input 𝐺 = (𝑉, 𝐸) //𝐺 is a DAG
{
search for a node 𝑉 with 𝑧𝑒𝑟𝑜 in-degree (no incoming
edges) and order it first in topological sorting
remove V from G
topological sort(G-{V}) // recursively compute topological
sorting append the ordering
}
+91-9319133134, [email protected]
Strongly Connected Components (SCC)
+91-9319133134, [email protected]
Strongly Connected Components (SCC)
+91-9319133134, [email protected]
Important Topics
+91-9319133134, [email protected]
Summary
• In this session we have seen that a graph is a very frequently used data structure
for many basic and significant algorithms.
• There are two standard approaches to represent a graph: Adjacency matrix and
adjacency lists which can be used to represent both directed as well as undirected
graph.
• Adjacency list provides a compact way to represent a sparse graph.
• BFS is a graph searching algorithm which start from any arbitrary vertex as a
starting vertex and visits all its adjacent vertices first and then moves at the
second level to visit all the unvisited vertices which are adjacent to vertices at the
first level vertices and so on.
+91-9319133134, [email protected]
+91-9319133134, [email protected]
Design and Analysis of Algorithms
Block-3 Unit-1
Graph Algorithms - II
Topics to be Covered
Introduction
Minimum Cost Spanning Tree (MCST)
Single Source Shortest Path
Maximum Bipartite Matching
Important Topics
Summary
• Graph is a non-linear data structure just like tree that consist of set of
vertices and edges and it has lot of applications in computer science and
in real world scenarios. Using graph algorithm easily find the shortest
path, cheapest path and predicted outputs. Real Life-example of Graph:
• Maps: You can think of map as a graph where intersections of roads are
vertices and connecting roads are edges.
• Social Networks: It is another example of graph structure where peoples
are connected based on the friendships, or some relationships.
• Internet: You can think of internet as graph structures, where there are
certain webpages and each webpages is connected through some link
• MCST_Kruskal(V, E, w)
• 𝐾←{}
• for each vertex 𝑣 ∈ 𝑉
• MAKE − SET(v)
• Sort the edge 𝐸 of 𝐺 in a non-decreasing order by weight 𝑤
• for the edge (𝑢, 𝑣) ∈ 𝐸, taken from the sorted-list
• if 𝐹𝐼𝑁𝐷 − 𝑆𝐸𝑇(𝑢) ≠ 𝐹𝐼𝑁𝐷 − 𝑆𝐸𝑇(𝑣)
• then 𝐾 ← 𝐾 𝖴 {(𝑢, 𝑣)}
• 𝑈𝑁𝐼𝑂𝑁(𝑢, 𝑣)
• return K
• PRIM’s Algorithm
• Prim’s algorithm based on the greedy algorithm to find the
minimum cost spanning tree & it finds safe edge .
• Minimum cost={0,5,8,15}
+91 – 9319133134, [email protected]
Graph Traversal Algorithms
• In real world life graph can be used to represent the cities and their
connections between each city.
• Vertices represents the cities and edges representing roads that connects these
vertices.
• The edges can have weights which may be the miles from one city to other
city. Suppose a person wants to drive from a city P to city Q.
• He may be interested to know the following queries:
• Is there any path exist from P to Q?
• If there are multiple paths from P to Q, then which is the shortest path?
• Dijkstra’s Algorithm
• Bellman Ford Algorithm
• Dijkstra’s Algorithm
• Dijkstra’s algorithm solves the single-source shortest path problem when
all edges have non-negative weights.
• It is a greedy algorithm’s similar to Prim’s algorithm and always choose
the path that are optimal right now not for future consequences.
• Bellman-Ford Algorithm
The Bellman-Ford algorithm solves the single-source
shortest-paths problem in case where edge weights may be
negative or there is a negative edge weight cycle in the
graph.
• Representation of graph
• Minimum cost spanning tree
• Dijkstra’s Algorithm
• Bellman-Ford Algorithm
• Maximum Bipartite Matching
• Binary Search Tree: A binary tree is binary search tree such that all the key smaller
than root are on left side and all the keys greater than root or on right side.
• No of comparison required to search any element in a binary search tree is depend
upon the number of levels in a binary search tree. We are searching for the key that
are already present in the binary search tree is successful search.
• Let’s take an example: Keys: 10, 20, 30 How many binary search tree possible.
T(n)=2nCn / n+1
• So there are 3 keys number of binary search tree possible = 5. Let’s draw five
possible binary search tree shown in below figure (a)-(e).
• Now we will find out the time complexities of running Dijkstra’s and Bellman
Ford algorithm for finding all pair shortest path to see which gives the best
result.
• From the two points it can be concluded that FWA is the best choice
for all pair shortest path problem when the graph is dense whereas
Dijkstra’s Algorithm is suitable when the graph is sparse and no
negative edge weight exist. For graph having negative edge weight
cycle the only choice among the three is Bellman Ford Algorithm.
• Introduction
• Naive or Brute Force Algorithm
• Rabin Karp Algorithm
• Knuth-Morris-Pratt Algorithm
• Important Topics
• Summary
• Best Case –O(n) where n is a length of a text. If sufficiently large base number
or a large prime number is used for computing hash value , there will be no
spurious hits and the hashed values would be distinct for both a pattern string and
a text substring. In such a case , the searching would take O(n) time.
https://www.geeksforge
eks.org/kmp-algorithm-
for-pattern-searching/
+91 – 9319133134, [email protected]
Important Topics
• Knuth-Morris-Pratt Algorithm
backward.
Block-4 Unit-1
Introduction to Complexity Classes
Topics to be Covered
• Introduction
• Some Preliminaries to P and NP Class of Problems
• Introduction to P and NP, and NP- Complete Problems
• The CNF Satisfiability Problem
• Important Topics
• Summary
• The following table displays the results of some input strings S generated at the
nondeterministic stage for the problem instance graph given in figure 1with the
total distance d value that is claimed to be a tour not greater than d(i.e. 18)and
passed to the function verify as an input.
• Introduction
• P Vs NP-Class of Problems
• Polynomial time reduction
• NP-Hard and NP-Complete problem
• Some well-known NP-Complete Problems-definitions
• Techniques (Steps) for proving NP-Completeness
• Proving NP-completeness (Decision problems)
• Important Topics
• Summary
+91 – 9319133134, [email protected]
Introduction
• NP is the set of decision problems (with „yes‟ or „no‟ answer) that can be
solved by a Nondeterministic algorithm (or Turing Machine) in Polynomial
time.
• Reductions-Formal definition:
• Reduction is a general technique for showing similarity
between problems. To show the similarity between
problems we need one base problem. A procedure which
is used to show the relationship (or similarity) between
problems is called Reduction step, and symbolically can
be written as
• 𝐸𝑎𝑠𝑦 → 𝑃
• 𝑀𝑒𝑑𝑖𝑢𝑚 → 𝑁𝑃
• 𝐻𝑎𝑟𝑑 → 𝑁𝑃 − 𝐶𝑜𝑚𝑝𝑙𝑒𝑡𝑒
• 𝐻𝑎𝑟𝑑𝑒𝑠𝑡 → 𝑁𝑃 − 𝐻𝑎𝑟d
• The following figure 6 shows a
relationship between P, NP,
NP-C and NP-Hard problems:
Source :https://www.baeldung.com/cs/p-np-np-complete-np-hard
• NP-Hard Problem
• A problem L is said to be NP-Hard problem if there is a
polynomial time reduction from
• already known NP-Hard problem 𝐿 ᇱ to the given
problem L.
• E′={( i, j) : I , j ∈ V and I ≠ j
𝐿 ∈ 𝑁𝑃
• L is NP Hard (that is every problem (say 𝐿') in NP is polynomial-time
reducible to L).
• P Vs NP-Class of Problems
• Polynomial time reduction
• NP-Hard and NP-Complete problem
• The CNF Satisfiability Problem
• Techniques (Steps) for proving NP- Completeness
• NP-completeness (Decision problems)
Block-4 Unit-13
Handling Intractability
Topics to be Covered
• Introduction
• Intelligent Exhaustive Search
• Approximation Algorithms Basics
• Important Topics
• Summary
• Approximation Ratio
• The term approximation ratio which can be defined as a ratio between
the results obtained by the approximation algorithm and the optimal
results of the algorithm. Consider a minimization optimization problem
P in which the main task is to minimize the given objective function.
• For example, vertex cover problem, graph coloring problem, etc. Are
combinatorial minimization optimization problem.