-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.nQueenProblem.cpp
56 lines (55 loc) · 1.27 KB
/
5.nQueenProblem.cpp
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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool isValid(int row,int col,vector<vector<char>>&board,int n){
int dup_row=row;
int dup_col=col;
while(col>=0 && row>=0){
if(board[row][col]=='Q')return false;
row--;
col--;
}
row=dup_row;
col=dup_col;
while(col>=0){
if(board[row][col]=='Q')return false;
col--;
}
col=dup_col;
while(row<n && col>=0){
if(board[row][col]=='Q')return false;
row++;
col--;
}
return true;
}
bool placeQueen(int col,vector<vector<char>>&board,int n){
if(col==n)return true;
for(int i=0;i<n;i++){
if(isValid(i,col,board,n)){
board[i][col]='Q';
bool check=placeQueen(col+1,board,n);
if(check==true)return true;
board[i][col]='.';
}
}
return false;
}
int main(){
int n;
cin>>n;
vector<vector<char>>board(n,vector<char>(n));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
board[i][j]='.';
}
}
placeQueen(0,board,n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<board[i][j]<<" ";
}
cout<<endl;
}
return 0;
}