# Untitled

unknown
c_cpp
2 years ago
1.6 kB
2
Indexable
Never
```//12604 - N-Queens M-Rooks Problem
#include <stdio.h>
#include <string.h>

int pos[10][2];//pos[位置的列數][是Queen還是Rook] = 位置的行數
int n, m;

int valid(int row, int level, int type){
if(level - 1 < 0) return 1;
for(int i = level-1; i >= 0; i--){
for(int j = 1; j <= 2; j++){//1代表Queen 2代表Rook
if(pos[i][j] != -1){//這一列的旗子是第j類
if(j == 1 || (j == 2 && type == 1)){
if(pos[i][j] == row) return 0;
if(pos[i][j] - row == level - i) return 0;
if(row - pos[i][j] == level - i) return 0;
}
else if(j == 2){
if(pos[i][j] == row) return 0;
}
}
}
}
return 1;
}

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

int ans = 0;
if(level == n+m) return 1;

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

if(r-1 >= 0){
pos[level][2] = i;
ans += solve(q, r-1, level+1);
pos[level][2] = -1;
}
}
}
return ans;
}

int main(){

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

memset(pos, -1, sizeof(pos));//上面沒有旗子時狀態為-1

printf("%d\n", solve(n, m, 0));
}
}
```