Lab 8 Ds
Lab 8 Ds
#include <iostream>
int factorial(int n) {
if (n == 0) { // Base case
return 1;
int main() {
int number;
// Calculating factorial
cout << "Factorial of " << number << " is " << result << endl;
return 0;
#include <iostream>
int factorial(int n) {
int main() {
int number;
return 0;
#include <iostream>
bool isOdd(int n) {
bool isEven(int n) {
int main() {
int number;
if (isEven(number))
else
return 0;
f(n)=1 if n=0
Example
#include <iostream>
int nestedRecursion(int n) {
if (n >= 0) return 1; // Base case, try with condition n<=0, it may crashed
int main() {
int number;
return 0;
int main() {
int number;
if (result != -1) {
} else {
return 0;
}
Backtracking Example: The N-Queens Problem
The N-Queens problem is a classic example where backtracking is used. The goal
is to place N queens on an NxN chessboard such that no two queens threaten each
other. This means:
Approach
1. Place a queen in the first row, then try to place another queen in the next
row.
2. For each row, place a queen in every column one by one and check whether
the current placement is valid (i.e., it doesn’t result in any queens attacking
each other).
3. If placing a queen in a particular column is not valid, backtrack and move
the queen to the next column.
4. Repeat the process for all rows until a solution is found or all possibilities
are exhausted.
#include <vector>
bool isSafe(const vector<vector<int> >& board, int row, int col, int n) {
if (board[i][col] == 1) {
return false;
}
}
if (board[i][j] == 1) {
return false;
if (board[i][j] == 1) {
return false;
return true;
if (row == n) {
return true;
}
return true;
board[row][col] = 0;
int main() {
int n;
cin >> n;
if (solveNQueens(board, 0, n)) {
printBoard(board, n);
} else {
return 0;