0% found this document useful (0 votes)
7 views9 pages

9thJanACALAB

The document outlines algorithms for finding the shortest path in a graph using Dijkstra's algorithm, detecting cycles in both undirected and directed graphs, and dynamic programming techniques for calculating binomial coefficients and longest common substrings. It includes time and space complexity analyses for each algorithm, as well as sample code implementations in C++. Additionally, it briefly mentions the Travelling Salesman Problem and its approach using dynamic programming.
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)
7 views9 pages

9thJanACALAB

The document outlines algorithms for finding the shortest path in a graph using Dijkstra's algorithm, detecting cycles in both undirected and directed graphs, and dynamic programming techniques for calculating binomial coefficients and longest common substrings. It includes time and space complexity analyses for each algorithm, as well as sample code implementations in C++. Additionally, it briefly mentions the Travelling Salesman Problem and its approach using dynamic programming.
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/ 9

Date: 26-12-2024

9.2 Shortest source to destination path


Algorithm:
1. Represent the graph using an adjacency matrix.
2. Maintain a distance array initialized to infinity (∞) for all nodes except the source (set to 0).
3. Use a visited array to keep track of processed nodes.
4. Select the node with the smallest tentative distance that hasn’t been visited.
5. Update the distances to its neighbors if a shorter path is found.
6. Mark the node as visited and repeat until all nodes are processed.
7. Output the distance array.
Time Complexity:
• O(V 2 ): Due to the adjacency matrix and nested loops for processing V nodes.
Space Complexity:
• O(V 2 ): For the adjacency matrix and arrays.
Code:
# include < iostream >
# include < limits >
using namespace std ;

const int INF = numeric_limits < int >:: max () ;

int f in dM in D is ta nc e ( int distance [] , bool visited [] , int V )


{
int minDist = INF , minIndex = -1;
for ( int i = 0; i < V ; i ++)
if (! visited [ i ] && distance [ i ] < minDist )
{
minDist = distance [ i ];
minIndex = i ;
}
return minIndex ;
}

void dijkstra ( int graph [100][100] , int V , int source )


{
int distance [ V ];
bool visited [ V ] = { false };

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


distance [ i ] = INF ;
distance [ source ] = 0;

for ( int count = 0; count < V - 1; count ++)


{
int u = fi nd Mi n Di st an c e ( distance , visited , V ) ;
visited [ u ] = true ;

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


if (! visited [ v ] && graph [ u ][ v ] && distance [ u ] != INF && distance [ u ] + graph [ u ][ v ] <
distance [ v ])
distance [ v ] = distance [ u ] + graph [ u ][ v ];
}

cout << " Shortest distances from source " << source << " : " << endl ;
for ( int i = 0; i < V ; i ++)
if ( distance [ i ] == INF )
cout << " Vertex " << i << " : INF " << endl ;
else

53
cout << " Vertex " << i << " : " << distance [ i ] << endl ;
}

int main ()
{
int V , E ;
cout << " Enter the number of vertices : " ;
cin >> V ;
cout << " Enter the number of edges : " ;
cin >> E ;

int graph [100][100] = {0};


cout << " Enter the edges (u , v , weight ) : " << endl ;
for ( int i = 0; i < E ; i ++)
{
int u , v , weight ;
cin >> u >> v >> weight ;
graph [ u ][ v ] = weight ;
graph [ v ][ u ] = weight ; // For u n d i r e c t e d graph
}

int source ;
cout << " Enter the source vertex : " ;
cin >> source ;

dijkstra ( graph , V , source ) ;

return 0;
}

Output 1:
Enter the number of vertices: 5
Enter the number of edges: 6
Enter the edges (u, v, weight):
0 1 2
0 2 4
1 2 1
1 3 7
2 4 3
3 4 1
Enter the source vertex: 0
Shortest distances from source 0:
Vertex 0: 0
Vertex 1: 2
Vertex 2: 3
Vertex 3: 9
Vertex 4: 6
Output 2:
Enter the number of vertices: 4
Enter the number of edges: 4
Enter the edges (u, v, weight):
0 1 1
1 2 2
0 2 4
2 3 1
Enter the source vertex: 0
Shortest distances from source 0:
Vertex 0: 0
Vertex 1: 1
Vertex 2: 3
Vertex 3: 4

54
9.3 Cycle Detection: Undirected Graph
Algorithm:
1. Represent the graph using an adjacency matrix graph.
2. Use a visited array to track visited nodes.
3. Perform DFS:
• If a visited node is encountered that is not the parent, a cycle is detected.
4. Repeat the process for all components of the graph.
Time Complexity:
• O(V 2 ): Adjacency matrix requires checking all nodes for edges.
Space Complexity:
• O(V ): Due to the visited and recStack arrays.
Code:
# include < iostream >
# include < cstring >
using namespace std ;

const int MAX = 100;

bool dfsUndirected ( int node , int parent , int graph [ MAX ][ MAX ] , bool visited [] , int n )
{
visited [ node ] = true ;

for ( int neighbor = 0; neighbor < n ; neighbor ++)


if ( graph [ node ][ neighbor ])
{
if (! visited [ neighbor ])
{
if ( dfsUndirected ( neighbor , node , graph , visited , n ) )
return true ;
}
else if ( neighbor != parent )
return true ;
}
return false ;
}

bool h a s C y c l e U n d i r e c t e d ( int n , int graph [ MAX ][ MAX ])


{
bool visited [ MAX ];
memset ( visited , false , sizeof ( visited ) ) ;

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


if (! visited [ i ])
if ( dfsUndirected (i , -1 , graph , visited , n ) )
return true ;
return false ;
}

int main ()
{
int n , m ;
cout << " Enter the number of nodes and edges : " ;
cin >> n >> m ;

int graph [ MAX ][ MAX ] = {0};


cout << " Enter the edges ( u v ) : " << endl ;
for ( int i = 0; i < m ; i ++)
{
int u , v ;
cin >> u >> v ;
graph [ u ][ v ] = graph [ v ][ u ] = 1;
}

55
if ( h a s C y c l e U n d i r e c t e d (n , graph ) )
cout << " Cycle detected in the undirected graph . " << endl ;
else
cout << " No cycle detected in the undirected graph . " << endl ;

return 0;
}

Output 1:
Enter the number of nodes and edges: 4 3
Enter the edges (u v):
0 1
1 2
2 0
Cycle detected in the undirected graph.
Output 2:
Enter the number of nodes and edges: 4 3
Enter the edges (u v):
0 1
1 2
2 3
No cycle detected in the undirected graph.

9.4 Cycle Detection: Directed Graph


Algorithm:
1. Represent the graph using an adjacency matrix graph.
2. Use two arrays:
• visited to track visited nodes.
• recStack to track nodes in the current recursion stack.
3. Perform DFS:
• If a node in the recursion stack is encountered, a cycle is detected.
Time Complexity:
• O(V 2 ): Adjacency matrix requires checking all nodes for edges.
Space Complexity:
• O(V ): Due to the visited and recStack arrays.
Code:
# include < iostream >
# include < cstring >
using namespace std ;

const int MAX = 100;

bool dfsDirected ( int node , int graph [ MAX ][ MAX ] , bool visited [] , bool recStack [] , int n )
{
visited [ node ] = true ;
recStack [ node ] = true ;

for ( int neighbor = 0; neighbor < n ; neighbor ++)


if ( graph [ node ][ neighbor ])
{
if (! visited [ neighbor ])
{
if ( dfsDirected ( neighbor , graph , visited , recStack , n ) )

56
{
return true ;
}
}
else if ( recStack [ neighbor ])
return true ;
}

recStack [ node ] = false ;


return false ;
}

bool h a s C y c l e D i r e c t e d ( int n , int graph [ MAX ][ MAX ])


{
bool visited [ MAX ];
bool recStack [ MAX ];
memset ( visited , false , sizeof ( visited ) ) ;
memset ( recStack , false , sizeof ( recStack ) ) ;

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


if (! visited [ i ])
if ( dfsDirected (i , graph , visited , recStack , n ) )
return true ;
return false ;
}

int main ()
{
int n , m ;
cout << " Enter the number of nodes and edges : " ;
cin >> n >> m ;

int graph [ MAX ][ MAX ] = {0};


cout << " Enter the edges ( u v ) : " << endl ;
for ( int i = 0; i < m ; i ++)
{
int u , v ;
cin >> u >> v ;
graph [ u ][ v ] = 1;
}

if ( h a s C y c l e D i r e c t e d (n , graph ) )
cout << " Cycle detected in the directed graph . " << endl ;
else
cout << " No cycle detected in the directed graph . " << endl ;

return 0;
}

Output 1:

Enter the number of nodes and edges: 4 4


Enter the edges (u v):
0 1
1 2
2 3
3 1
Cycle detected in the directed graph.
Output 2:
Enter the number of nodes and edges: 4 4
Enter the edges (u v):
0 1
1 2
2 3
3 4
No cycle detected in the directed graph.

57
10 Dynamic Programming
10.1 Binomial Co efficient
Algorithm:
1. Define a DP table dp[n + 1][k + 1]:

dp[i][j] stores C(i, j), the number of ways to choose j items from i items.

2. Initialize the base cases:


• C(i, 0) = 1 (choosing 0 items from i items).
• C(i, i) = 1 (choosing all i items from i items).
3. Use the recurrence relation:
C(i, j) = C(i − 1, j − 1) + C(i − 1, j)
• C(i − 1, j − 1): Include the current item.
• C(i − 1, j): Exclude the current item.
4. Fill the DP table iteratively for all i from 0 to n and j from 0 to min(i, k).
5. Return dp[n][k].
Time Complexity:
• O(n · k): Each cell in the DP table is computed once.
Space Complexity:
• O(n · k): To store the DP table.
Code:
# include < iostream >
# include < cstring >
using namespace std ;

const int MAX = 100;

int b i n o m i a l C o e f f i c i e n t ( int n , int k )


{
int dp [ MAX ][ MAX ];
memset ( dp , 0 , sizeof ( dp ) ) ;

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


{
dp [ i ][0] = 1;
if ( i <= k )
{
dp [ i ][ i ] = 1;
}
}

for ( int i = 1; i <= n ; i ++)


for ( int j = 1; j <= min (i , k ) ; j ++)
dp [ i ][ j ] = dp [ i - 1][ j - 1] + dp [ i - 1][ j ];

return dp [ n ][ k ];
}

int main ()
{
int n , k ;
cout << " Enter the values of n and k : " ;
cin >> n >> k ;

if ( k > n )
{

58
cout << " Invalid input : k cannot be greater than n . " << endl ;
return 0;
}

cout << " Binomial Coefficient C ( " << n << " , " << k << " ) = " << b i n o m i a l C o e f f i c i e n t (n , k ) << endl ;

return 0;
}

Output 1:
Enter the values of n and k: 5 2
Binomial Coefficient C(5, 2) = 10
Output 2:
Enter the values of n and k: 6 3
Binomial Coefficient C(6, 3) = 20

10.2 Longest Common Substring


Algorithm:
1. Define a DP table dp[m+1][n+1]:

dp[i][j] stores the length of the longest common substring ending at indices i − 1 and j − 1.

2. Initialize all values of dp to 0.


3. Traverse both strings A and B:
• If A[i − 1] == B[j − 1]:
dp[i][j] = dp[i-1][j-1] + 1
Update the maximum length and track the substring.
• Else:
dp[i][j] = 0
4. The value of maxLen gives the length of the longest common substring.
Time Complexity:
• O(m · n): m is the length of string A and n is the length of string B.
Space Complexity:
• O(m · n): For the DP table.
Code:
# include < iostream >
# include < cstring >
using namespace std ;

const int MAX = 1000;

int l o n g e s t C o m m o n S u b s t r i n g ( char A [] , char B [] , int m , int n )


{
int dp [ MAX ][ MAX ];
memset ( dp , 0 , sizeof ( dp ) ) ;
int maxLen = 0;

for ( int i = 1; i <= m ; i ++)


for ( int j = 1; j <= n ; j ++)
if ( A [ i - 1] == B [ j - 1])
{
dp [ i ][ j ] = dp [ i - 1][ j - 1] + 1;
maxLen = max ( maxLen , dp [ i ][ j ]) ;
}
else

59
dp [ i ][ j ] = 0;

return maxLen ;
}

int main ()
{
char A [ MAX ] , B [ MAX ];
cout << " Enter the first string : " ;
cin >> A ;
cout << " Enter the second string : " ;
cin >> B ;

int m = strlen ( A ) , n = strlen ( B ) ;


cout << " Length of Longest Common Substring : " << l o n g e s t C o m m o n S u b s t r i n g (A , B , m , n ) << endl ;

return 0;
}

Output 1:
Enter the first string: abcde
Enter the second string: abfce
Length of Longest Common Substring: 2
Output 2:
Enter the first string: abcxyz
Enter the second string: xyzabc
Length of Longest Common Substring: 3

10.3 Travelling Salesman Problem


Algorithm:
1. Represent the graph using an adjacency matrix graph[i][j], where graph[i][j] is the distance from city i to city j.
2. Use a DP table dp[mask][i], where mask represents the set of visited cities and i is the current city.
3. Initialize the base case: dp[1 ¡¡ i][i] = 0 for all cities i.
4. Use the recurrence relation:

dp[mask][i] = min dp[mask][i], dp[prevMask][j] + graph[j][i]

where prevMask = mask ˆ(1 ¡¡ i) and j is the previous city.


5. Compute the minimum cost of returning to the starting city after visiting all cities.
Time Complexity:
• O(n · 2n ): We compute the cost for each subset of cities and for each city.
Space Complexity:
• O(n · 2n ): The DP table requires space proportional to the number of subsets and cities.
Code:
# include < iostream >
# include < limits >
# include < cstring >
using namespace std ;

const int INF = numeric_limits < int >:: max () ;


const int MAX = 20;

int tsp ( int graph [ MAX ][ MAX ] , int n )


{
int dp [1 << MAX ][ MAX ];
memset ( dp , INF , sizeof ( dp ) ) ;

60
for ( int i = 0; i < n ; i ++)
dp [1 << i ][ i ] = 0;

for ( int mask = 1; mask < (1 << n ) ; mask ++)


for ( int i = 0; i < n ; i ++)
if ( mask & (1 << i ) )
for ( int j = 0; j < n ; j ++)
if (( mask & (1 << j ) ) && i != j )
dp [ mask ][ i ] = min ( dp [ mask ][ i ] , dp [ mask ^ (1 << i ) ][ j ] + graph [ j ][ i ]) ;

int result = INF ;


for ( int i = 1; i < n ; i ++)
result = min ( result , dp [(1 << n ) - 1][ i ] + graph [ i ][0]) ;

return result ;
}

int main ()
{
int n ;
cout << " Enter the number of cities : " ;
cin >> n ;

int graph [ MAX ][ MAX ];


cout << " Enter the distance matrix : " << endl ;
for ( int i = 0; i < n ; i ++)
for ( int j = 0; j < n ; j ++)
cin >> graph [ i ][ j ];

int result = tsp ( graph , n ) ;


cout << " The minimum cost of the Travelling Salesman Problem is : " << result << endl ;

return 0;
}

Output 1:
Enter the number of cities: 4
Enter the distance matrix:
0 10 15 20
10 0 35 25
15 35 0 30
20 25 30 0
The minimum cost of the Travelling Salesman Problem is: 80

Output 2:
Enter the number of cities: 3
Enter the distance matrix:
0 1 2
1 0 3
2 3 0
The minimum cost of the Travelling Salesman Problem is: 6

61

You might also like