Cod sursa(job #3355092)

Utilizator Razvan25555Razvan Razvan25555 Data 21 mai 2026 18:56:39
Problema Problema Damelor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.21 kb
// Ionascu George-Razvan

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

vector <vector <int>> a;
ifstream fin("damesah.in");
ofstream fout("damesah.out");

bool col_empty(int n, int col) {
    for (int i = 0; i < n; i++) {
        if (a[i][col] == 1) {
            return false;
        }
    }
    return true;
}

bool diag_empty(int n, int curr_x, int curr_y) {
    int tmpx, tmpy;

    //stanga sus
    tmpx = curr_x - 1;
    tmpy = curr_y - 1;
    while(tmpx >= 0 && tmpy >= 0) {
        if (a[tmpx][tmpy] == 1) {
            return false;
        }
        tmpx--;
        tmpy--;
    }

    //stanga jos
    tmpx = curr_x + 1;
    tmpy = curr_y - 1;
    while(tmpx < n && tmpy >= 0) {
        if (a[tmpx][tmpy] == 1) {
            return false;
        }
        tmpx++;
        tmpy--;
    }

    //dreapta sus
    tmpx = curr_x - 1;
    tmpy = curr_y + 1;
    while(tmpx >= 0 && tmpy < n) {
        if (a[tmpx][tmpy] == 1) {
            return false;
        }
        tmpx--;
        tmpy++;
    }

    //dreapta jos
    tmpx = curr_x + 1;
    tmpy = curr_y + 1;
    while(tmpx < n && tmpy < n) {
        if (a[tmpx][tmpy] == 1) {
            return false;
        }
        tmpx++;
        tmpy++;
    }

    return true;
}

void bkt(int n, int start, bool &printed, int &cnt) {
    if (start == n) {
        if (printed == false) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (a[i][j] == 1) {
                        fout << j + 1 << " ";
                    }
                }
            }
            fout << "\n";
            printed = true;
        }

        cnt++;
    }

    for (int i = 0; i < n; i++) {
        if (col_empty(n, i) == true && diag_empty(n, start, i) == true) {
            
            a[start][i] = 1;

            bkt(n, start + 1, printed, cnt);

            a[start][i] = 0;
        }
    }
}

int main() {
    int n, cnt = 0;
    bool printed = false;
    fin >> n;

    a.resize(n, vector<int> (n, 0));

    bkt(n, 0, printed, cnt);

    fout << cnt << "\n";

    fin.close();
    fout.close();
    return 0;
}