-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN_Queens problem.cpp
More file actions
143 lines (115 loc) · 1.79 KB
/
N_Queens problem.cpp
File metadata and controls
143 lines (115 loc) · 1.79 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#include<iostream>
using namespace std;
//struct Hetman {
// int x;
// int y;
//};
const int PUSTE = -1;
//int abs(int a, int b)
//{
// return a - b < 0 ? -(a - b) : (a - b);
//}
bool isValid(int **board,int N, int row, int col)
{
int j = col;
int jLeft = j;
int jRight = j;
bool moveRight = true;
bool moveLeft = true;
while (row > 0)
{
row--;
if (jLeft - 1 >= 0)
{
jLeft--;
}
else
{
moveLeft = false;
}
if (jRight + 1 < N)
{
jRight++;
}
else
{
moveRight = false;
}
if (board[row][j] != PUSTE)
{
return false;
}
if (moveLeft && board[row][jLeft] != PUSTE)
{
return false;
}
if (moveRight && board[row][jRight] != PUSTE)
{
return false;
}
}
return true;
}
void wyswietl_plansze(int** board, int N)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (board[i][j] == 1) //MA HETMANA
{
cout << "[]";
}
else
{
(i + j) % 2 == 0 ? cout << " " : cout << "##";
}
}
cout << '\n';
}
//cout << "--------------";
cout << '\n';
}
int szukaj_rozwiazan(int **board,int N, int row)
{
if (row == N)
{
wyswietl_plansze(board, N);
return 1;
}
int counter = 0;
for (int col = 0; col < N; col++)
{
if (isValid(board, N, row, col))
{
board[row][col] = 1;
//wyswietl_plansze(board, N);
counter += szukaj_rozwiazan(board, N, row + 1);
board[row][col] = PUSTE;
}
}
return counter;
}
int main()
{
short N;
cout << "N: ";
cin >> N;
int** board = new int* [N];
for (int i = 0; i < N; i++)
{
*(board + i) = new int[N];
for (int j = 0; j < N; j++)
{
*(*(board + i) + j) = PUSTE;
}
}
//cout << "ILE ROZW: " << szukaj_rozwiazan(board, N, 0);
szukaj_rozwiazan(board, N, 0);
for (int i = 0; i < N; i++)
{
delete[] board[i];
}
delete[] board;
return 0;
}