-
-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathN_Queen_Problem.cpp
More file actions
90 lines (73 loc) · 1.39 KB
/
N_Queen_Problem.cpp
File metadata and controls
90 lines (73 loc) · 1.39 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <iostream>
#include <vector>
using namespace std;
void addSolution(vector<vector<int>> &board, int n, vector<vector<int>> &ans)
{
vector<int> temp;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
temp.push_back(board[i][j]);
}
}
ans.push_back(temp);
}
bool isSafe(int row, int col, vector<vector<int>> &board, int n)
{
int x = row;
int y= col;
while(y>=0)
{
if(board[x][y]==1)
return false;
y--;
}
x = row;
y = col;
while(x>=0 && y>=0)
{
if(board[x][y]==1)
return false;
x--;
y--;
}
x = row;
y = col;
while(x<n && y>=0)
{
if(board[x][y]==1)
return false;
x++;
y--;
}
return true;
}
void solve(int col, vector<vector<int>> &board, vector<vector<int>> &ans, int n)
{
if (col == n)
{
addSolution(board, n, ans);
return;
}
for (int i = 0; i < n; i++)
{
if (isSafe(i,col, board, n))
{
board[i][col] = 1;
solve(col+1, board,ans,n);
board[i][col] = 0;
}
}
}
vector<vector<int>> NQueens(int n)
{
vector<vector<int>> board(n, vector<int>(n, 0));
vector<vector<int>> ans;
solve(0, board, ans, n);
return ans;
}
int main()
{
return 0;
}