Cod sursa(job #2197853)

Utilizator M1st1cVlad Vaculin M1st1c Data 22 aprilie 2018 22:57:30
Problema Problema Damelor Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
/* C/C++ program to solve N Queen Problem using
backtracking */
#include<bits/stdc++.h>
using namespace std;
ifstream fin("damesah.in");
ofstream fout("damesah.out");
int N;
int s;
int board[14][14];
void printSolution()
{
    static int k = 1;
    s = k++;
    if(k>=3)
        return ;
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        if(board[i][j]){
            fout <<j+1<<" ";
        }

    }
    fout <<"\n";
}
bool isSafe(int row, int col)
{
    int i, j;
    for (i = 0; i < row; i++)
        if (board[i][col])
            return false;

    for (i=row, j=col; i>=0 && j>=0; i--, j--)
        if (board[i][j])
            return false;
    for (i=row, j=col; j<N && i>=0; i--, j++)
        if (board[i][j])
            return false;

    return true;
}
bool solveNQUtil(int row)
{
    if (row == N)
    {
        printSolution();
        return true;
    }
    bool res = false;
    for (int i = 0; i < N; i++){
        if ( isSafe(row, i) )
        {
            board[row][i] = 1;
            res = solveNQUtil(row + 1) || res;
            board[row][i] = 0;
        }
    }
    return res;
}

void solveNQ()
{
    solveNQUtil(0);


    return ;
}

int main()
{
    fin >> N;
    solveNQ();
    fout << s;
    return 0;
}