#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 8
void printSolution(int board[N]);
bool isSafe(int board[N], int row, int col);
bool solveNQUtil(int board[N], int col);
void printSolution(int board[N]) {
static int solutionNumber = 1;
printf("Solution #%d:\n", solutionNumber++);
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], int row, int col) {
int i, j;
for (i = 0; i < col; i++)
if (board[i] == row)
return false;
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[j] == i)
return false;
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[j] == i)
return false;
return true;
}
bool solveNQUtil(int board[N], int col) {
if (col >= N) {
printSolution(board);
return true;
}
bool res = false;
for (int i = 0; i < N; i++) {
if (isSafe(board, i, col)) {
board[col] = i;
res = solveNQUtil(board, col + 1) || res;
board[col] = -1;
}
}
return res;
}
bool solveNQ() {
int board[N];
for (int i = 0; i < N; i++) board[i] = -1;
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
return true;
}
int main() {
solveNQ();
return 0;
}