Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active April 29, 2025 18:01
Show Gist options
  • Save sunmeat/b8eb4708f4c2d794052ebba98932868d to your computer and use it in GitHub Desktop.
Save sunmeat/b8eb4708f4c2d794052ebba98932868d to your computer and use it in GitHub Desktop.
8 queens C++
#include <conio.h>
#include <iostream>
using namespace std;
int z = 0; // кількість варіантів розміщення
char check(int A[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (A[i] == A[j] && i != j && A[i] != 0)
return 0;
if (A[i] + i == A[j] + j && i != j && A[i] != 0 && A[j] != 0)
return 0;
if (A[i] - i == A[j] - j && i != j && A[i] != 0 && A[j] != 0)
return 0;
}
}
return 1;
}
void print_field(int A[], int n)
{
int i, j;
for (i = 0; i < n; i++)
{
cout << "-";
for (j = 0; j < n; j++)
cout << "--";
cout << endl;
for (j = 1; j < A[i]; j++)
cout << "| ";
cout << "|F";
for (j = A[i]; j < n; j++)
cout << "| ";
cout << "|\n";
}
for (j = 0; j < n; j++)
cout << "--";
cout << "-\n\n";
z++;
}
void build(int A[], const int n)
{
int i, k;
for (k = 0; A[k] != 0 && k < n; k++);
if (k >= n)
{
print_field(A, n);
return;
}
int* B = new int[n];
for (i = 0; i < k; i++)
B[i] = A[i];
for (i = k; i < n; i++)
B[i] = 0;
for (i = 1; i <= n; i++)
{
B[k] = i;
if (check(B, n))
build(B, n);
}
delete[] B;
}
int main()
{
setlocale(0, "UKR");
system("title Queens");
const int n = 8;
int A[n];
for (int i = 0; i < n; i++)
A[i] = 0;
cout << "Розташування:\n";
build(A, n);
cout << "Всього варіантів: " << z << "\n\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment