0% found this document useful (0 votes)
8 views3 pages

Experiment No. 10: Program Name

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Experiment No. 10: Program Name

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Experiment No.

10
Program Name:
Write a program in C to implement N Queen Problem using Backtracking

Theory Concept:
The N-Queens problem is a classic combinatorial problem in computer science and
mathematics. It involves placing N queens on an N×N chessboard such that no two queens
attack each other.
Rules:
1. A queen in chess can move any number of squares:
o Horizontally
o Vertically
o Diagonally
2. The challenge is to position the queens so that:
o No two queens share the same row.
o No two queens share the same column.
o No two queens share the same diagonal.
Objective:
The goal is to find a way to place all N queens on the board while satisfying the above
constraints.

Implementation:
#include<stdio.h>
#include<stdbool.h>
#define N 8
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%c ", board[i][j] ? 'Q' : '.');
}
printf("\n");
}
printf("\n");
}
bool isSafe(int board[N][N], int row, int col)
{
for (int i = 0; i < col; i++)
if (board[row][i])
return false;
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
for (int i = row, j = col; i < N && j >= 0; i++, j--)
if (board[i][j])
return false;
return true;
}
bool solveNQueensUtil(int board[N][N], int col)
{
if (col >= N)
return true;
for (int i = 0; i < N; i++)
{
if (isSafe(board, i, col))
{
board[i][col] = 1;
if (solveNQueensUtil(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}
bool solveNQueens()
{
int board[N][N] = {0};
if (!solveNQueensUtil(board, 0))
{
printf("Solution does not exist.\n");
return false;
}
printSolution(board);
return true;
}
int main()
{
solveNQueens();
return 0;
}

Output/Conclusion:
Q.......
......Q.
....Q...
.......Q
.Q......
...Q....
.....Q..
..Q.....

You might also like