Pagini recente » Cod sursa (job #583081) | Cod sursa (job #2822292) | Cod sursa (job #2143369) | Monitorul de evaluare | Cod sursa (job #3310386)
#include <fstream>
#include <vector>
#include <string>
using namespace std;
ifstream cin("damesah.in");
ofstream cout("damesah.out");
class NQueens {
private:
int n;
vector<int> queens;
vector<string> firstSolution;
int totalSolutions;
bool foundFirst;
bool isSafe(int row, int col) {
for (int i = 0; i < row; i++) {
if (queens[i] == col ||
queens[i] - i == col - row ||
queens[i] + i == col + row) {
return false;
}
}
return true;
}
void solve(int row) {
if (row == n) {
totalSolutions++;
if (!foundFirst) {
foundFirst = true;
firstSolution.clear();
for (int i = 0; i < n; i++) {
string line(n, '.');
line[queens[i]] = 'Q';
firstSolution.push_back(line);
}
}
return;
}
for (int col = 0; col < n; col++) {
if (isSafe(row, col)) {
queens[row] = col;
solve(row + 1);
}
}
}
public:
NQueens(int size) : n(size), queens(size), totalSolutions(0), foundFirst(false) {}
void findSolutions() {
solve(0);
}
void displayResults() {
if (totalSolutions == 0) {
return;
}
for (const string& row : firstSolution) {
cout << row << endl;
}
cout << totalSolutions << endl;
}
};
int main() {
int n;
cin >> n;
NQueens nqueens(n);
nqueens.findSolutions();
nqueens.displayResults();
return 0;
}