蓝桥杯 ALGO-125 算法训练 王、后传说

算法训练 王、后传说  

时间限制:1.0s   内存限制:256.0MB

问题描述
  地球人都知道,在国际象棋中,后如同太阳,光芒四射,威风八面,它能控制横、坚、斜线位置。
  看过清宫戏的中国人都知道,后宫乃步步惊心的险恶之地。各皇后都有自己的势力范围,但也总能找到相安无事的办法。
  所有中国人都知道,皇权神圣,伴君如伴虎,触龙颜者死......
  现在有一个n*n的皇宫,国王占据他所在位置及周围的共9个格子,这些格子皇后不能使用(如果国王在王宫的边上,占用的格子可能不到9个)。当然,皇后也不会攻击国王。
  现在知道了国王的位置(x,y)(国王位于第x行第y列,x,y的起始行和列为1),请问,有多少种方案放置n个皇后,使她们不能互相攻击。

输入格式
  一行,三个整数,皇宫的规模及表示国王的位置

输出格式
  一个整数,表示放置n个皇后的方案数

样例输入
8 2 2

扫描二维码关注公众号,回复: 8686779 查看本文章

样例输出
10

数据规模和约定
  n<=12

#include <stdio.h>

int n;
int x, y;
int queens[15];
int n_queens;
int solutions;

int abs(int x)
{
    return x < 0 ? -x : x;
}

int is_valid(int row, int col)
{
    if (abs(row - x) <= 1 && abs(col - y) <= 1)
        return 0;
    for (int i = 0; i < n_queens; ++i)
    {
        if (col == queens[i] || abs(row - (i+1)) == abs(col - queens[i]))
            return 0;
    }
    return 1;
}

void put_queen(int row)
{
    if (row > n)
    {
        solutions++;
        return;
    }

    for (int col = 1; col <= n; ++col)
    {
        if (is_valid(row, col))
        {
            queens[n_queens++] = col;
            put_queen(row + 1);
            n_queens--;
        }
    }
}

int main()
{
    scanf("%d %d %d", &n, &x, &y);

    n_queens = 0;
    solutions = 0;
    put_queen(1);

    printf("%d", solutions);

    return 0;
}
发布了221 篇原创文章 · 获赞 40 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/liulizhi1996/article/details/104012700
今日推荐