Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.4 kB
3
Indexable
Never
//12604 - N-Queens M-Rooks Problem   
#include <stdio.h>

int chess[10][10];
int n, m, ans = 0;

int valid(int row, int level){
    for(int i = level-1; i >= 0; i--){
        for(int j = 0; j < n+m; j++){
            if(chess[i][j] == 1){
                if(j == row) return 0;
                if(j - row == level - i) return 0;
                if(row - j == level - i) return 0;
            }
            if(chess[i][j] == 2){
                if(j == row) return 0;
            }
        }
    }
    return 1;
}

int solve(int q, int r, int level){

    if(level == n+m) return 1;
    
    for(int i = 0; i < n+m; i++){
        if(valid(i, level+1)){
            if(q-1 >= 0){
                chess[i][level+1] = 1;
                return ans += solve(q-1, r, level+1);
                chess[i][level+1] = 0;
            }
            if(r-1 >= 0){
                chess[i][level+1] = 2;
                return ans += solve(q, r-1, level+1);                    
                chess[i][level+1] = 0;
            }
        }
    }
    return ans;
}

int main(){

    while(scanf("%d%d", &n, &m) != EOF){

        for(int i = 0; i < n+m; i++){
            for(int j = 0; j < n+m; j++){
                chess[i][j] = 0;
            }
        }
        solve(n, m, 0);
        printf("%d\n", ans);
        ans = 0;
    }
}