DAAPractical
DAAPractical
Write a program to find shortest path from your home to college using Bellman-Ford
algorithm.
The Bellman–Ford algorithm is like a guide that helps you find the shortest path from one city to all
other cities, even if some roads have negative lengths. It’s like a GPS for computers, useful for figuring
out the quickest way to get from one point to another in a network. In this article, we’ll take a closer
look at how this algorithm works and why it’s so handy in solving everyday problems.
Algorithm:
1. Initialization:
o Set the distance to the source vertex d(source)=0d(source) = 0d(source)=0.
o Set the distance to all other vertices d(v)=∞d(v) = \inftyd(v)=∞ (infinity).
2. Relaxation:
o For each vertex vvv in the graph, do the following for V−1V-1V−1 iterations (where
VVV is the number of vertices):
For each edge (u,v)(u, v)(u,v) with weight www:
If d(u)+w<d(v)d(u) + w < d(v)d(u)+w<d(v):
Update d(v)=d(u)+wd(v) = d(u) + wd(v)=d(u)+w.
3. Check for Negative Weight Cycles:
o For each edge (u,v)(u, v)(u,v) with weight www:
If d(u)+w<d(v)d(u) + w < d(v)d(u)+w<d(v):
A negative weight cycle exists, and you can report that.
Program:
#include <bits/stdc++.h>
struct Edge {
};
struct Graph {
int V, E;
};
graph->V = V;
graph->E = E;
return graph;
int V = graph->V;
int E = graph->E;
int dist[V];
// vertices as INFINITE
dist[i] = INT_MAX;
dist[src] = 0;
int u = graph->edge[j].src;
int v = graph->edge[j].dest;
if (dist[u] != INT_MAX
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
if (dist[u] != INT_MAX
// return
}
printArr(dist, V);
return;
// Driver's code
int main()
cout<<"URN:2203395\n\n";
graph->edge[0].src = 0;
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
// add edge 1-2 (or B-C in above figure)
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
// add edge 4-3 (or E-D in above figure)
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
// Function call
BellmanFord(graph, 0);
return 0;
}
PRACTICAL NO: 10
Output:
PRACTICAL NO: 10
Here knapsack is like a container or a bag. Suppose we have given some items which have some weights
or profits. We have to put some items in the knapsack in such a way total value produces a maximum
profit.
Algorithm:
1. Initialization:
o Create a 2D array dp where dp[i][j] will hold the maximum value that can be attained
with the first i items and a maximum weight of j.
2. Base Case:
o If there are no items or the capacity is 0, then the maximum value is 0:
dp[0][j] = 0 for all j
dp[i][0] = 0 for all i
3. Filling the DP Table:
o For each item iii from 1 to nnn:
For each capacity jjj from 1 to WWW:
If the weight of the item w[i−1]w[i-1]w[i−1] is less than or equal to jjj:
Consider two cases:
1. Including the item: dp[i-1][j - w[i-1]] + v[i-1]
2. Excluding the item: dp[i-1][j]
Take the maximum of both cases:
dp[i][j] = max(dp[i-1][j], dp[i-1][j - w[i-1]] + v[i-1])
If the weight of the item w[i−1]w[i-1]w[i−1] is greater than jjj:
Exclude the item:
dp[i][j] = dp[i-1][j]
Result:
The value at dp[n][W] will contain the maximum value that can be attained with n items and capacity W.
Program:
#include <iostream>
#include <vector>
{
// Base case: no items left or capacity is 0
if (n == 0 || W == 0)
return 0;
if (weight[n - 1] > W)
return max(value[n - 1]
+ knapsackRecursive(weight, value,
W - weight[n - 1],
n - 1),
int main()
cout<<"URN:2203395\n\n";
vector<int> weight = { 1, 2, 4, 5 };
vector<int> value = { 5, 4, 8, 6 };
// Knapsack capacity
int W = 5;
weight.size())
<< endl;
return 0;
}
PRACTICAL NO: 11
Input Graph: 4
1 4
1 11 9 18
0 2 2 5 5 13 7
16
5 2 2
3 6
Output Graph:
5 2 2
0 3 6 7
Output:
PRACTICAL NO: 11
Write a program to find the shortest path of the multistage graph using dynamic
programming.
A Multistage graph is a directed, weighted graph in which the nodes can be divided into a set of stages
such that all edges are from a stage to next stage only (In other words there is no edge between vertices
of same stage and from a vertex of current stage to previous stage).
Algorithm:
1. Initialization:
o Let d[i]d[i]d[i] be the minimum distance from the source to vertex iii.
o Set d[start]=0d[start] = 0d[start]=0 (the distance to the source vertex) and d[i]=∞d[i] =
\inftyd[i]=∞ for all other vertices.
2. Backward Calculation:
o Start from the second-to-last stage and move backwards to the first stage:
For each vertex jjj in the current stage:
Update the distances to its connected vertices in the next stage using:
d[j]=min(d[j],cost(j,k)+d[k])d[j] = \min(d[j], \text{cost}(j, k) +
d[k])d[j]=min(d[j],cost(j,k)+d[k])
Here, kkk are the vertices in the next stage that are reachable from jjj.
3. Result:
o The shortest path from the source to the destination is found in d[end]d[end]d[end].
Program:
#include<bits/stdc++.h>
#define N 8
// N-1.
dist[N-1] = 0;
// destination (N-1)
dist[i] = INF;
// i to N-1.
if (graph[i][j] == INF)
continue;
// We apply equation to
// so far.
dist[i] = min(dist[i], graph[i][j] + dist[j]);
return dist[0];
// Driver code
int main()
cout<<"URN:2203395\n\n";
int graph[N][N] =
return 0;
}
PRACTICAL NO: 12
Graph:
10
0 3
5 1
1 2
Output:
PRACTICAL NO: 12
Write a program to find minimum distance between different cities of your state using
FloydWarshall algorithm.
It is used to find the shortest paths between all pairs of nodes in a weighted graph. This algorithm is
highly efficient and can handle graphs with both positive and negative edge weights, making it a
versatile tool for solving a wide range of network and connectivity problems.
Algorithm:
1. Initialization:
o Create a distance matrix DDD such that:
D[i][j]=w(i,j)D[i][j] = w(i, j)D[i][j]=w(i,j) if there is an edge from iii to jjj.
D[i][j]=0D[i][j] = 0D[i][j]=0 if i=ji = ji=j (the distance from a vertex to itself).
D[i][j]=∞D[i][j] = \inftyD[i][j]=∞ if there is no edge between iii and jjj.
2. Dynamic Programming Update:
o For each intermediate vertex kkk from 1 to VVV:
For each source vertex iii from 1 to VVV:
For each destination vertex jjj from 1 to VVV:
Update the distance:
D[i][j]=min(D[i][j],D[i][k]+D[k][j])D[i][j] = \min(D[i][j],
D[i][k] + D[k][j])D[i][j]=min(D[i][j],D[i][k]+D[k][j])
This checks if the path from iii to jjj through kkk is shorter than the
currently known shortest path.
3. Result:
o The distance matrix DDD will contain the shortest path distances between every pair of
vertices.
Program:
#include <iostream>
#include <limits.h>
#include <vector>
int V = dist.size();
if (dist[i][j] == INF)
<< "\t";
else
int V = graph.size();
if (dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j])
printSolution(dist);
int main()
cout<<"URN:2203395\n\n";
vector<vector<int>> graph = {{0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF,
0}};
floydWarshall(graph);
return 0;
}
PRACTICAL NO: 13
Output:
4 queen problem
8 queen problem
PRACTICAL NO: 13
Write a program to find the solution to the 8 queen’s problem using the backtracking.
Algorithm:
Program:
#include <iostream>
#include <vector>
}
cout << endl;
int n = board.size();
return true;
int n = board.size();
if (row >= n) {
printBoard(board);
return;
board[row][col] = 0; // Backtrack
int main() {
cout<<"URN:2203395\n\n";
int n;
cin>>n;
solveNQueens(board, 0);
return 0;
}
PRACTICAL NO: 14
Output:
PRACTICAL NO: 14
Subset sum can also be thought of as a special case of the 0–1 Knapsack problem. For each item, there
are two possibilities:
Include the current element in the subset and recur for the remaining elements with the remaining
Sum.
Exclude the current element from the subset and recur for the remaining elements.
Algorithm:
1. Input:
o A list of integers (nums).
o A target sum (target).
2. Function subsetSum(nums, n, target):
o Parameters:
nums: the list of integers.
n: the number of elements in the list.
target: the desired sum we want to achieve.
3. Base Cases:
o If target == 0:
Return true (a subset with the given sum has been found).
o If n == 0 and target != 0:
Return false (no elements left to consider, and target not met).
4. Recursive Cases:
o If the last element (nums[n - 1]) is greater than target:
Call subsetSum(nums, n - 1, target) (ignore the last element).
o Otherwise:
Check two scenarios:
1. Exclude the last element:
Call subsetSum(nums, n - 1, target).
2. Include the last element:
Call subsetSum(nums, n - 1, target - nums[n -
1]).
Return the logical OR of both scenarios.
5. Output:
o If subsetSum returns true, print "Found a subset with the given sum".
o Otherwise, print "No subset with the given sum".
Program:
#include <iostream>
#include <vector>
using namespace std;
// Base Cases
// Check if we can form the sum by either including or excluding the last element
int main() {
cout<<"URN:2203395\n\n";
int n = nums.size();
if (subsetSum(nums, n, target)) {
cout << "Found a subset with the given sum " << target << endl;
} else {
cout << "No subset with the given sum " << target << endl;
return 0;
}
PRACTICAL NO: 15
Graph:
1 3
5
0
2 4
Output:
PRCATICAL NO: 15
Write a program to use a queue to store the node and mark it as 'visited' until all its
neighbours (vertices that are directly connected to it) are marked. Implement by using bfs
algorithm for a graph
Breadth-First Search (BFS) is an algorithm used to explore nodes and edges of a graph. It operates by
starting at a specified node (often called the "source") and exploring all of its neighbors at the present
depth prior to moving on to nodes at the next depth level. This makes BFS particularly useful for finding
the shortest path in an unweighted graph.
Algorithm:
1. Initialization:
o Create a queue and a boolean array to track visited nodes.
o Enqueue the starting node and mark it as visited.
2. BFS Loop:
o While the queue is not empty:
Dequeue a node from the front of the queue.
Process the node (e.g., print it or perform some operation).
For each unvisited neighbor of the current node:
Mark the neighbor as visited.
Enqueue the neighbor.
3. End: The algorithm continues until all reachable nodes from the source node have been
processed.
Program:
#include <iostream>
#include <vector>
#include <queue>
q.pop(); // Dequeue it
cout << "Visited: " << node << endl; // Process the node
int main() {
cout<<"URN:2203395\n\n";
graph[5] = {3};
vector<bool> visited(vertices, false); // Track visited nodes
return 0;
}
PRACTICAL NO: 16
Graph:
Output:
PRACTICAL NO: 16
Depth-First Search (DFS) is an algorithm used to explore nodes and edges of a graph. It starts at a
selected node (often called the "source") and explores as far as possible along each branch before
backtracking. This makes DFS particularly useful for tasks such as pathfinding, topological sorting, and
solving puzzles.
Algorithm:
1. Initialization:
Program:
#include <iostream>
#include <vector>
cout << "Visited: " << node << endl; // Process the node
int main() {
cout<<"URN:2203395\n\n";
graph[5] = {3};
return 0;