Skip to content

Commit 7a82eb4

Browse files
authored
Create NQueenProblem.cpp
1 parent 23c8357 commit 7a82eb4

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Backtracking/NQueenProblem.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
#define N 4
2+
#include <stdbool.h>
3+
#include <stdio.h>
4+
5+
6+
void printSolution(int board[N][N])
7+
{
8+
for (int i = 0; i < N; i++) {
9+
for (int j = 0; j < N; j++)
10+
printf(" %d ", board[i][j]);
11+
printf("\n");
12+
}
13+
}
14+
15+
bool isSafe(int board[N][N], int row, int col)
16+
{
17+
int i, j;
18+
19+
for (i = 0; i < col; i++)
20+
if (board[row][i])
21+
return false;
22+
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
23+
if (board[i][j])
24+
return false;
25+
26+
for (i = row, j = col; j >= 0 && i < N; i++, j--)
27+
if (board[i][j])
28+
return false;
29+
30+
return true;
31+
}
32+
33+
bool solveNQUtil(int board[N][N], int col)
34+
{
35+
if (col >= N)
36+
return true;
37+
38+
39+
for (int i = 0; i < N; i++) {
40+
if (isSafe(board, i, col)) {
41+
board[i][col] = 1;
42+
if (solveNQUtil(board, col + 1))
43+
return true;
44+
45+
board[i][col] = 0;
46+
}
47+
}
48+
return false;
49+
}
50+
51+
52+
bool solveNQ()
53+
{
54+
int board[N][N] = { { 0, 0, 0, 0 },
55+
{ 0, 0, 0, 0 },
56+
{ 0, 0, 0, 0 },
57+
{ 0, 0, 0, 0 } };
58+
59+
if (solveNQUtil(board, 0) == false) {
60+
printf("Solution does not exist");
61+
return false;
62+
}
63+
64+
printSolution(board);
65+
return true;
66+
}
67+
68+
69+
int main()
70+
{
71+
solveNQ();
72+
return 0;
73+
}

0 commit comments

Comments
 (0)