-
Notifications
You must be signed in to change notification settings - Fork 0
/
N Queens - Fill Remaining.cpp
109 lines (86 loc) · 2.09 KB
/
N Queens - Fill Remaining.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <bits/stdc++.h>
using namespace std;
int n ;
vector<bool> row, col ; // , dia_1, dia_2 ;
bool chech_dia(vector<vector<int> > & b, int x, int y)
{
for(int i = x+1, j = y+1 ; i < n and j < n ; i++, j++)
{
if(b[i][j])
return false ;
}
for(int i = x-1, j = y-1 ; i >= 0 and j >= 0 ; i--, j--)
{
if(b[i][j])
return false ;
}
for(int i = x+1, j = y-1 ; i < n and j >= 0 ; i++, j--)
{
if(b[i][j])
return false ;
}
for(int i = x-1, j = y+1 ; i >= 0 and j < n ; i--, j++)
{
if(b[i][j])
return false ;
}
return true ;
}
bool fill_queen(vector<vector<int> > & b, int queen)
{
if(queen == n)
return true ;
for(int i = 0 ; i < n ; i++)
{
if(row[i] == 0)
{
for(int j = 0 ; j < n ; j++)
{
if(col[j] == 0 and chech_dia(b, i, j))
{
b[i][j] = 1 ;
row[i] = 1 ;
col[j] = 1 ;
if(fill_queen(b, queen+1))
return true ;
b[i][j] = 0 ;
row[i] = 0 ;
col[j] = 0 ;
}
}
}
}
return false ;
}
int main()
{
cin >> n ;
vector<vector<int> > b(n, vector<int>(n, 0));
row = vector<bool>(n, 0);
col = vector<bool>(n, 0);
/*dia_1 = vector<bool>(n, 0);
dia_2 = vector<bool>(n, 0);*/
int queen = 0 ;
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < n ; j++)
{
cin >> b[i][j] ;
if(b[i][j])
{
queen++ ;
row[i] = 1 ;
col[j] = 1 ;
}
}
}
fill_queen(b, queen);
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < n ; j++)
{
cout << b[i][j] << " " ;
}
cout << endl ;
}
}