Daa Exp7
Daa Exp7
Experiment No. 7
ALGORITHM:
N-Queen:
It involves placing N chess queens on an N×N chessboard in such a
way that no two queens attack each other. This means that no two
queens share the same row, column, or diagonal.
Sum Of Subset:
Given a set of positive integers and a target sum, the task is to find a
subset of the given set such that the sum of its elements is equal to
the given target sum.
PSEUDOCODE
N-QUEEN:
nQueen(board, col):
if col >= N:
printBoard(board)
return true
for each row in board:
if isSafe(row, col):
board[row][col] = 1
if nQueen(board, col + 1):
return true
board[row][col] = 0
return false
isSafe(row, col):
for each queen in the same row:
if queen is placed:
return false
for each (i, j) in upper diagonal:
if queen is placed at (i, j):
return false
for each (i, j) in lower diagonal:
if queen is placed at (i, j):
return false
return true
printBoard(board):
for each row in board:
for each cell in row:
if cell is queen:
print "Q "
else:
print ". "
print new line
SUM OF SUBSETS
procedure subsetSum(arr, targetSum):
subsetSumtill(arr, [], 0, 0, targetSum)
void sumOfSubsets(int arr[], int subset[], int n, int subsetSize, int total, int
targetSum, int currentIndex) {
// Check if the subset size exceeds the array size
if (subsetSize > n) {
printf("Error: Subset size exceeds the array size.\n");
return;
}
// Base case: If the total equals the target sum, print the subset
if (total == targetSum) {
printSubset(subset, subsetSize);
return;
}
// Base case: If the current index equals the array size, return
if (currentIndex == n) {
return;
}
// Exclude the current element from the subset and recursively call
sumOfSubsets
sumOfSubsets(arr, subset, n, subsetSize, total, targetSum,
currentIndex + 1);
}
int main() {
printf("1.N-QUEEN'S PROBLEM\n");
int N;
printf("Number of queens:");
scanf("%d",&N);
printf("\n");
solveNQ(N);
for(int i=0;i<n;i++){
printf("Element no. %d:",i+1);
scanf("%d",&arr[i]);
}
int targetSum;
printf("Target sum?:");
scanf("%d",&targetSum);
return 0;
}
RESULT:
DRY RUN: N-Queen:
Sum of Subset:
CONCLUSION:
Using the backtracking method, I have solved the n-Queens and Sum of Subsets
problem.