算法训练 王、后传说

来源:互联网 发布:电网络理论视频 编辑:程序博客网 时间:2024/04/25 19:34
问题描述
  地球人都知道,在国际象棋中,后如同太阳,光芒四射,威风八面,它能控制横、坚、斜线位置。
  看过清宫戏的中国人都知道,后宫乃步步惊心的险恶之地。各皇后都有自己的势力范围,但也总能找到相安无事的办法。
  所有中国人都知道,皇权神圣,伴君如伴虎,触龙颜者死......
  现在有一个n*n的皇宫,国王占据他所在位置及周围的共9个格子,这些格子皇后不能使用(如果国王在王宫的边上,占用的格子可能不到9个)。当然,皇后也不会攻击国王。
  现在知道了国王的位置(x,y)(国王位于第x行第y列,x,y的起始行和列为1),请问,有多少种方案放置n个皇后,使她们不能互相攻击。
输入格式
  一行,三个整数,皇宫的规模及表示国王的位置
输出格式
  一个整数,表示放置n个皇后的方案数
样例输入
8 2 2
样例输出
10
数据规模和约定
  n<=12
#include <stdio.h>#define INF 1<<30#define MAXSIZE 20int n, x, y, ans;int palace[MAXSIZE][MAXSIZE];void init(){int i, j;for(i = 0; i < MAXSIZE; i ++){for(j = 0; j < MAXSIZE; j ++){palace[i][j] = 0;}}for(i = x-1; i <= x+1; i++){for(j = y-1; j <= y+1; j ++){palace[i][j] = INF;} }ans = 0;}int judge(int row, int col){int i, j;for(i = row-1, j = col-1; i >= 1 && j >= 1; i --, j --){if(palace[i][j] == 1){return 0;}}for(i = row-1, j = col+1; i >= 1 && j <= n; i --, j ++){if(palace[i][j] == 1){return 0;}}for(i = row-1, j = col; i >= 1; i --){if(palace[i][j] == 1){return 0;}}return 1;}void countScheme(int r){if(r > n){ans ++;return;}int i;for(i = 1; i <= n; i ++){if(palace[r][i] == INF){continue;}if(judge(r, i)){palace[r][i] = 1;countScheme(r+1);palace[r][i] = 0;}else{continue;}}}int main(){scanf("%d%d%d", &n, &x, &y);init();countScheme(1);printf("%d", ans);return 0;}

1 0
原创粉丝点击