0% found this document useful (0 votes)
19 views2 pages

ADS&AA Week-10

Uploaded by

Mohammed Zameer
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)
19 views2 pages

ADS&AA Week-10

Uploaded by

Mohammed Zameer
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/ 2

Week-10

10. Implement N-Queens Problem Using Backtracking


Program:
#include <stdio.h>
#include <stdbool.h>

#define N 8 // You can change this value to solve for different sizes of the chessboard

// Function to print the chessboard


void printSolution(int board[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (board[i][j] == 1)
printf("Q "); // 'Q' represents a queen
else
printf(". "); // '.' represents an empty space
}
printf("\n");
}
printf("\n");
}

// Function to check if a queen can be placed on board[row][col]


bool isSafe(int board[N][N], int row, int col) {
int i, j;

// Check the same column in previous rows


for (i = 0; i < row; i++)
if (board[i][col] == 1)
return false;

// Check upper left diagonal


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return false;

// Check upper right diagonal


for (i = row, j = col; i >= 0 && j < N; i--, j++)
if (board[i][j] == 1)
return false;

return true;
}

// A recursive utility function to solve the N-Queens problem


bool solveNQueensUtil(int board[N][N], int row) {
// Base case: All queens are placed
if (row >= N)
return true;
// Consider this row and try placing a queen in each column
for (int col = 0; col < N; col++) {
// Check if the queen can be placed at board[row][col]
if (isSafe(board, row, col)) {
// Place the queen
board[row][col] = 1;

// Recur to place the rest of the queens


if (solveNQueensUtil(board, row + 1))
return true;

// If placing queen at board[row][col] doesn't lead to a solution, backtrack


board[row][col] = 0; // Remove the queen
}
}

// If the queen cannot be placed in any column in this row, return false
return false;
}

// This function solves the N-Queens problem using backtracking


bool solveNQueens() {
int board[N][N] = {0}; // Initialize the board with all 0s

// Solve the N-Queens problem starting from the first row


if (!solveNQueensUtil(board, 0)) {
printf("Solution does not exist.\n");
return false;
}

// Print the solution


printSolution(board);
return true;
}

int main() {
solveNQueens();
return 0;
}

Output:
Q.......
....Q...
.......Q
.....Q..
..Q.....
......Q.
.Q......
...Q....

You might also like