NOI:八皇后问题

一、题目大意

按列排序找出所有八皇后解

二、解题思路

定义dfs(i)为放置第i列的行为,深搜

三、代码

/**
以列为基准搜索
**/

#include<iostream>
using namespace std;

const int MAX = 104;
const int N = 8;
int grad[10][10];

int dir[8][2] = {{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,-1},{-1,1}};
int cnt;
int ans[MAX];
int out_of_edge(int x, int y)
{
    if(x < 0 || x >= 8 || y < 0 || y >= 8)
        return 1;
    return 0;
}
int ok(int r, int c)
{
    for(int i=0; i<8; i++)
    {
        int nx, ny;
        nx = r + dir[i][0];
        ny = c + dir[i][1];
        while(!out_of_edge(nx, ny))
        {
            if(grad[nx][ny])
                return 0;
            nx = nx + dir[i][0];
            ny = ny + dir[i][1];
        }
    }
    return 1;
}
void dfs(int c)
{
    if(c == N)
    {
        for(int j=0; j<N; j++)
        {
            for(int i=0; i<N; i++)
            {
                if(grad[i][j])
                {
                    ans[cnt] = ans[cnt] * 10 + i+1;
                    break;
                }
            }
        }
        cnt++;
    }
    for(int r=0; r<N; r++)
    {
        if(ok(r, c))
        {
            grad[r][c] = 1;
            dfs(c+1);
            grad[r][c] = 0;
        }
    }
}
int main()
{
    cnt = 0;
    dfs(0);
    int T;
    cin >> T;
    int n;
    while(T--)
    {
        cin >> n;
        cout << ans[n-1] << endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值