N皇后问题

1. 问题描述:
N皇后问题是一个经典的问题,在一个N*N的棋盘上放置N个皇后,每行一个并使其不能互相攻击(同一行、同一列、同一斜线上的皇后都会自动攻击)

本人使用的是回溯法,另外还有高效的解法见转载的博客
http://blog.csdn.net/hacker00011000/article/details/51582300

2. Code

#include <iostream>

#define N 20

using namespace std;
bool arr[N][N] = {0}; 
int count = 0;

//判断有没有冲突 
bool Correct(int row, int col, int n)
{
    int j = 0;
    //行
    for (int i=1; i<=n; ++i)
    {
        if (arr[row][i]) 
            return false;
    }
    //列
    for (int i=1; i<=n; ++i)
    {
        if (arr[i][col]) 
            return false;
    }

    //左上角
    for (int i=row-1, j=col-1; i>=1 && j>=1; --i,--j)
    {
        if (arr[i][j])
            return false; 
    }
    //右下角
    for (int i=row+1, j=col+1; i<=n && j<=n; ++i,++j)
    {
        if (arr[i][j])
            return false; 
    }

    //右上角
    for (int i=row-1, j=col+1; i>=1 && j<=n; --i,++j) 
    {
        if (arr[i][j])
            return false; 
    }
    //左下角
    for (int i=row+1, j=col-1; i<=n && j>=1; ++i,--j)
    {
        if (arr[i][j])
            return false; 
    }

    return true;
}

//从第row(0)行开始选,一共有n行 
void DFS(int row, int n)
{
    //n行选完得到一个解 
    if (row == n+1)
    {
        ++count;
        //traverse
        for (int i=1; i<=n; ++i)
        { 
            for (int j=1; j<=n; ++j)
            {
                cout << arr[i][j]; 
            }
            cout << endl;
        }
        cout << "*****" << endl; 
        return;
    }

    //DFS
    //每一行可以选择n列
    for (int col=1; col<=n; ++col)
    {
        //如果可以选择 
        if (Correct(row, col, n))
        {
            arr[row][col] = true; 
            DFS(row+1, n); 
            arr[row][col] = false; 
        }
    }
}

int main()
{
    cout << "******N皇后问题******" << endl; 
    int n;
    cin >> n;

    DFS(1, n); 
    cout << count << endl;

    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值