Skip to content

Commit cd56f0f

Browse files
authored
Create N-queen_backtracking.cpp
1 parent 4ca1b67 commit cd56f0f

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

N-queen_backtracking.cpp

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
#include <bits/stdc++.h>
2+
#include <iostream>
3+
using namespace std;
4+
const int m=10;
5+
int board[10][10];
6+
7+
void printSolution(int board[][10], int N)
8+
{
9+
for (int i = 0; i < N; i++)
10+
{
11+
for (int j = 0; j < N; j++)
12+
printf(" %d ", board[i][j]);
13+
printf("\n");
14+
}
15+
}
16+
17+
bool is_attacked(int x,int y,int board[][10], int N){
18+
for(int i=0; i<N; i++){
19+
for(int j=0; j<N; j++){
20+
if(i==x || j==y || (i+j)==(x+y)||(i-j)==(x-y)){
21+
if(board[i][j]==1)
22+
return true;
23+
}
24+
}
25+
}
26+
return false;
27+
}
28+
29+
bool N_queens(int board[][m], int row , int N){
30+
if(row==N)
31+
return true;
32+
for(int i=0;i<N;i++){
33+
for(int j=0;j<N;j++){
34+
if(is_attacked(i,j,board,N)){
35+
continue;
36+
}
37+
board[i][j]=1;
38+
if(N_queens(board,row+1,N)){
39+
return true;
40+
}
41+
board[i][j]=0;
42+
43+
}
44+
}
45+
return false;
46+
}
47+
48+
int main(){
49+
int N;
50+
cin >> N;
51+
52+
53+
for(int i=0;i<=N;i++)
54+
for(int j=0;j<=N;j++)
55+
board[i][j]=0;
56+
57+
58+
59+
if(N_queens(board,0,N)){
60+
cout << "YES" << "\n";
61+
printSolution(board,N);
62+
}
63+
else
64+
cout << "NO";
65+
66+
return 0;
67+
68+
}

0 commit comments

Comments
 (0)