ADD LAB MANUAL 8,9
ADD LAB MANUAL 8,9
AIM :
Write a C++ program for implementing N-queen program and subset sum problem using
backtracking method.
1.N-QUEEN PROBLEM :
ALGORITHM :
1. Start from the leftmost column.
2.For each column, attempt to place a queen in each row.
3.Check if placing a queen on the current row and column is safe (no other queens should attack this
position).
4.If placing the queen is safe, move to the next column and repeat the process.
5. If placing a queen in any row of the current column isn't possible, backtrack to the previous column.
6. Repeat the above steps until all queens are placed or no solution exists.
PROGRAM :
#include <iostream>
#include <vector>
using namespace std;
bool isSafe(vector<vector<int>>& board, int row, int col, int N) {
for (int i = 0; i < col; i++)
if (board[row][i] == 1) return false;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1) return false;
for (int i = row, j = col; i < N && j >= 0; i++, j--)
if (board[i][j] == 1) return false;
return true;
}
bool solveNQueenUtil(vector<vector<int>>& board, int col, int N) {
if (col >= N) return true;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col, N)) {
board[i][col] = 1;
if (solveNQueenUtil(board, col + 1, N))
return true;
board[i][col] = 0;
}
}
return false;
}
void solveNQueen(int N) {
vector<vector<int>> board(N, vector<int>(N, 0));
if (solveNQueenUtil(board, 0, N)) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
cout << board[i][j] << " ";
cout << endl;
}
} else {
cout << "Solution does not exist." << endl;
}
}
int main() {
int N;
cout << "Enter the number of queens: ";
cin >> N;
solveNQueen(N);
return 0;
}
OUTPUT :
Enter the number of queens: 4
0100
0001
1000
0010
2. SUBSET SUM PROBLEM
ALGORITHM :
1. Use backtracking to explore subsets by including or excluding elements.
2. For each element, add it to the current subset and check if it matches the target sum.
3. If it matches, store the subset.
4. If the sum exceeds the target, backtrack.
5. Repeat until all subsets are considered.
PROGRAM :
#include <iostream>
#include <vector>
using namespace std;
void subsetSum(vector<int>& nums, int index, int target, vector<int>& currentSubset) {
if (target == 0) {
cout << "{ ";
for (int num : currentSubset) cout << num << " ";
cout << "}" << endl;
return;
}
if (index >= nums.size() || target < 0) return;
currentSubset.push_back(nums[index]);
subsetSum(nums, index + 1, target - nums[index], currentSubset);
currentSubset.pop_back();
subsetSum(nums, index + 1, target, currentSubset);
}
int main() {
int n, target;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> nums(n);
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> nums[i];
cout << "Enter target sum: ";
cin >> target;
vector<int> currentSubset;
cout << "Subsets with sum " << target << ":" << endl;
subsetSum(nums, 0, target, currentSubset);
return 0;
}
OUTPUT :
Enter the number of elements: 5
Enter the elements: 1 2 3 4 5
Enter target sum: 5
Subsets with sum 5:
{14}
{23}
{5}
RESULT :
Thus, the N-queen problem and subset sum problem was successfully executed and output was
verified.
EX.NO : 09 BRANCH AND BOUND – ASSIGNMENT PROBLEM ,TRAVELING SELSMAN
DATE : PROBLEM
AIM :
Write a C++ program to implement assignment and traveling selsman problem using branch and
bound method .
1.ASSIGNMENT PROBLEM :
ALGORITHM :
1.Initialize a cost matrix where each element represents the cost of assigning a particular task to an
agent.
3.Use a priority queue to store the nodes of the search tree and explore each possibility in a best-
first search order based on the minimum cost.
4.Update the bound after each assignment to minimize the cost further.
PROGRAM :
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
struct Node {
vector<int> path;
int cost;
int bound;
int level;
};
int calculateCost(vector<vector<int>>& costMatrix, vector<int>& path, int n) {
int totalCost = 0;
for (int i = 0; i < path.size() - 1; i++) {
totalCost += costMatrix[path[i]][path[i+1]];
}
return totalCost;
}
int calculateBound(vector<vector<int>>& costMatrix, vector<int>& path, int n) {
int lowerBound = 0;
for (int i = 0; i < n; i++) {
if (find(path.begin(), path.end(), i) == path.end()) {
int minCost = INT_MAX;
for (int j = 0; j < n; j++) {
if (find(path.begin(), path.end(), j) == path.end())
minCost = min(minCost, costMatrix[i][j]);
}
lowerBound += minCost;
}
}
return lowerBound;
}
void branchAndBoundAssignment(vector<vector<int>>& costMatrix, int n) {
priority_queue<Node> pq;
Node root;
root.path = {-1};
root.cost = 0;
root.bound = calculateBound(costMatrix, root.path, n);
root.level = 0;
pq.push(root);
int minCost = INT_MAX;
vector<int> bestPath;
while (!pq.empty()) {
Node minNode = pq.top();
pq.pop();
if (minNode.bound < minCost) {
for (int i = 0; i < n; i++) {
if (find(minNode.path.begin(), minNode.path.end(), i) == minNode.path.end()) {
Node childNode = minNode;
childNode.path.push_back(i);
childNode.cost = calculateCost(costMatrix, childNode.path, n);
childNode.bound = childNode.cost + calculateBound(costMatrix, childNode.path, n);
childNode.level = minNode.level + 1;
if (childNode.level == n && childNode.cost < minCost) {
minCost = childNode.cost;
bestPath = childNode.path;
} else if (childNode.bound < minCost) {
pq.push(childNode);
}
}
}
}
}
cout << "Minimum cost: " << minCost << endl;
cout << "Assignment: ";
for (int i = 1; i < bestPath.size(); i++) {
cout << bestPath[i] << " ";
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of agents/tasks: ";
cin >> n;
vector<vector<int>> costMatrix(n, vector<int>(n));
cout << "Enter the cost matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> costMatrix[i][j];
}
}
branchAndBoundAssignment(costMatrix, n);
return 0;
}
OUTPUT :
Enter the number of agents/tasks: 3
Enter the cost matrix:
927
643
581
Minimum cost: 13
Assignment: 1 2 0
2.TRAVELING SELESMAN PROBLEM :
ALGORITHM :
1.Initialize a cost matrix where each element represents the distance between two cities.
2.Calculate the lower bound for each potential route by summing the minimum edge costs.
3.Use Branch and Bound to explore each path, calculating costs and bounds to prune unpromising
paths.
4.Explore nodes in a best-first search manner based on minimum bound.
5.Stop when the shortest tour that visits all cities is found.
PROGRAM :
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
struct TSPNode {
vector<int> path;
int cost;
int bound;
int level;
bool operator<(const TSPNode& other) const {
return bound > other.bound;
}
};
int tspCalculateBound(vector<vector<int>>& distanceMatrix, vector<int>& path, int n) {
int lowerBound = 0;
for (int i = 0; i < n; i++) {
if (find(path.begin(), path.end(), i) == path.end()) {
int minCost = INT_MAX;
for (int j = 0; j < n; j++) {
if (i != j) minCost = min(minCost, distanceMatrix[i][j]);
}
lowerBound += minCost;
}
}
return lowerBound;
}
void branchAndBoundTSP(vector<vector<int>>& distanceMatrix, int n) {
priority_queue<TSPNode> pq;
TSPNode root;
root.path = {0};
root.cost = 0;
root.bound = tspCalculateBound(distanceMatrix, root.path, n);
root.level = 0;
pq.push(root);
int minCost = INT_MAX;
vector<int> bestPath;
while (!pq.empty()) {
TSPNode minNode = pq.top();
pq.pop();
if (minNode.bound < minCost) {
for (int i = 1; i < n; i++) {
if (find(minNode.path.begin(), minNode.path.end(), i) == minNode.path.end()) {
TSPNode childNode = minNode;
childNode.path.push_back(i);
childNode.cost = minNode.cost + distanceMatrix[minNode.path.back()][i];
childNode.bound = childNode.cost + tspCalculateBound(distanceMatrix,
childNode.path, n);
childNode.level = minNode.level + 1;
if (childNode.level == n - 1) {
childNode.cost += distanceMatrix[childNode.path.back()][0];
if (childNode.cost < minCost) {
minCost = childNode.cost;
bestPath = childNode.path;
}
} else if (childNode.bound < minCost) {
pq.push(childNode);
}
}
}
}
}
cout << "Minimum cost: " << minCost << endl;
cout << "Tour: ";
for (int city : bestPath) cout << city << " ";
cout << "0" << endl;
}
int main() {
int n;
cout << "Enter the number of cities: ";
cin >> n;
vector<vector<int>> distanceMatrix(n, vector<int>(n));
cout << "Enter the distance matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> distanceMatrix[i][j];
}
}
branchAndBoundTSP(distanceMatrix, n);
return 0;
}
OUTPUT:
Enter the number of cities: 4
Enter the distance matrix:
0 20 42 35
20 0 30 34
42 30 0 12
35 34 12 0
Minimum cost: 97
Tour: 0 1 3 2 0
RESULT :
Thus, the above programs are successfully executed and output is verified.