Pagini recente » Cod sursa (job #2863742) | Cod sursa (job #2919989) | Cod sursa (job #1586331)
#include <fstream>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <bitset>
#include <cmath>
using namespace std;
typedef pair<int, int> Position;
static constexpr size_t maxN()
{
return 4;
}
bitset<maxN()> queens[maxN()];
vector<Position> vQueenPositions;
static bool areAttacking(const Position& p1, const Position& p2)
{
//std::cout << (abs(p1.first - p2.first) == abs(p1.second - p2.second)) << " --- " << p1.first << " : " << p1.second << " -- " << p2.first << " : " << p2.second << std::endl;
return abs(p1.first - p2.first) == abs(p1.second - p2.second) || p1.first == p2.first || p1.second == p2.second;
}
int numSol = 0;
fstream fout("damesah.out", fstream::out);
static void solveQueens(int n, int numQueens)
{
if (numQueens == 0)
{
if (numSol == 0)
{
for (auto pos : vQueenPositions)
{
fout << pos.second + 1 << " ";
}
fout << std::endl;
}
numSol ++;
return;
}
//for (int i=0; i<n; ++i)
int i = numQueens - 1;
{
for (int j=0; j<n; ++j)
{
//if (i != j)
{
bool isSafe = true;
Position p;
for (auto pos : vQueenPositions)
{
//std::cout << pos.first << " -- " << pos.second << " ";
if (areAttacking(pos, {i, j}))
{
//std::cout << pos.first << " " << pos.second << " -- " << i << " " << j << std::endl;
isSafe = false;
break;
}
}
//std::cout << isSafe << endl;
if (isSafe)
{
queens[i][j] = true;
vQueenPositions.push_back({i, j});
solveQueens(n, numQueens - 1);
vQueenPositions.pop_back();
queens[i][j] = false;
}
}
}
}
}
int main()
{
fstream fin("damesah.in", fstream::in);
int n;
fin >> n;
//cout << n << std::endl;
//std::cout << areAttacking({0, 3}, {1, 2}) << std::endl;
//std::getchar();
vQueenPositions.reserve(n);
solveQueens(n, n);
fout << numSol << std::endl;
return 0;
}