Cod sursa(job #3310387)

Utilizator risxdrzBanica Albert risxdrz Data 13 septembrie 2025 14:39:09
Problema Problema Damelor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <vector>
using namespace std;

class NQueens {
private:
    int n;
    vector<int> queens;
    vector<int> 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 = queens;
            }
            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() {
        for (int i = 0; i < n; i++) {
            cout << firstSolution[i] + 1;
            if (i < n - 1) cout << " ";
        }
        cout << endl;
        cout << totalSolutions << endl;
    }
};

int main() {
    int n;
    cin >> n;
    
    NQueens nqueens(n);
    nqueens.findSolutions();
    nqueens.displayResults();
    
    return 0;
}