-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathnQueen.cpp
More file actions
66 lines (50 loc) · 1.12 KB
/
nQueen.cpp
File metadata and controls
66 lines (50 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
//backtracking
int ct;
void print(vector<vector<bool>> &grid, int n)
{
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(grid[i][j]) cout<<"Q";
else cout<<".";
}
cout<<endl;
}
}
bool isSafe(vector<vector<bool>> &grid, int r, int c, int n){
//column
for(int i=r-1; i>=0; i--){
if(grid[i][c]) return false;
}
//left diagonal
for(int i=r-1,j=c-1; i>=0&& j>=0; i--,j--){
if(grid[i][j]) return false;
}
//right diagonal
for(int i=r-1,j=c+1; i>=0&&j<n; i--,j++){
if(grid[i][j]) return false;
}
return true;
}
void countNQueen(vector<vector<bool>> &grid, int curr_row, int n){
if(curr_row==n){
ct++;
print(grid, n);
cout<<"\n\n";
}
for(int i=0; i<n; i++){
if(isSafe(grid, curr_row, i, n)){
grid[curr_row][i]=true;
countNQueen(grid, curr_row+1, n);
grid[curr_row][i]=false;
}
}
}
int main(){
int n; cin>>n;
vector<vector<bool>>grid(n, vector<bool>(n,0));
ct=0;
countNQueen(grid,0,n);
cout<<ct<<endl;
}