Skip to content

Commit 5d810b1

Browse files
committed
the 4-queen backtracking solution algorithm
1 parent 42f8c40 commit 5d810b1

File tree

2 files changed

+61
-5
lines changed

2 files changed

+61
-5
lines changed

backtracking/4-n-queen.cpp

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,53 @@
1-
#define N 4
1+
#define N 12
22
#include<stdio.h>
33
#include<stdbool.h>
44

55

6+
void printSolution(int board[N][N]){
7+
for(int i = 0; i < N; i++){
8+
for(int j = 0; j < N; j++){
9+
if(board[i][j]) printf("Q ");
10+
else printf(". ");
11+
}
12+
printf("\n");
13+
}
14+
}
15+
16+
bool isSafe(int board[N][N], int row, int col){
17+
18+
int i, j;
19+
20+
//checking left since the queen is already placed (no need to check the right side)
21+
for(i = 0; i < col; i++) if(board[row][i]) return false;
22+
23+
24+
//check the upper diagonal
25+
for(i = row, j = col; i >= 0 && j >= 0; i--, j--) if(board[i][j]) return false;
26+
27+
28+
//check the lower diagonal
29+
for(i = row, j = col; j >= 0 && i < N ; i++, j--) if(board[i][j]) return false;
30+
31+
32+
return true;
33+
34+
}
35+
636
bool solveNQUtil(int board[N][N], int col){
737

838
if(col >= N) return true;
39+
40+
for(int i = 0; i < N; i++){
41+
if(isSafe(board, i, col)){
42+
43+
board[i][col] = 1;
44+
45+
if(solveNQUtil(board, col+1)) return true;
46+
47+
//backtrack to 0
48+
board[i][col] = 0;
49+
}
50+
}
951

1052
return false;
1153
}
@@ -14,12 +56,26 @@ bool solveNQUtil(int board[N][N], int col){
1456
bool solveNQ(){
1557

1658
int board[N][N] = {
17-
{0, 0, 0, 0,},
18-
{0, 0, 0, 0,},
19-
{0, 0, 0, 0,},
20-
{0, 0, 0, 0,}
59+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
60+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
61+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
62+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
63+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
64+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
65+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
66+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
67+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
68+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
69+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
70+
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
2171
};
2272

73+
if(solveNQUtil(board, 0) == false){
74+
printf("No solution possible");
75+
return false;
76+
}
77+
78+
printSolution(board);
2379
return true;
2480

2581
}

backtracking/4-n-queen.exe

1.46 KB
Binary file not shown.

0 commit comments

Comments
 (0)