Aoa Exp8 04
Aoa Exp8 04
08
SE2/S2/04
Theory:
The N Queen is the problem of placing N chess queens on an N×N chessboard so that no
two queens attack each other.
The expected output is in form of a matrix that has ‘Q’s for the blocks where queens are
placed and the empty spaces are represented by ‘.’s . For example, the following is the
output matrix for the above 4 queen solution.
..Q.
Q...
...Q
.Q..
The idea is to place queens one by one in different columns, starting from the leftmost
column. When we place a queen in a column, we check for clashes with already placed
queens. In the current column, if we find a row for which there is no clash, we mark this
row and column as part of the solution. If we do not find such a row due to clashes, then
we backtrack and return false.
Algorithm:
Code :
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
printf("\n");
if (board[i][col] == 1)
return false;
if (board[i][j] == 1)
return false;
if (board[i][j] == 1)
return false;
}
Experiment No. 08
return true;
if (row >= N)
return true;
board[row][col] = 1;
return true;
board[row][col] = 0;
return false;
void solveNQueen(int N) {
board[i][j] = 0;
if (solveNQueens(board, N, 0))
printBoard(board, N);
else
Experiment No. 08
free(board[i]);
free(board);
int main() {
int N;
scanf("%d", &N);
if (N <= 0) {
return 1;
solveNQueen(N);
return 0;
Output:
Experiment No. 08
Conclusion:
The N-Queen problem is best solved using backtracking, which tries placing queens one
by one and goes back (backtracks) if a placement is not valid.