首页 > 其他 > 详细

九度 1254:N皇后问题

时间:2014-03-08 01:06:29      阅读:618      评论:0      收藏:0      [点我收藏+]

Leetcode 原题.

这里 N 最大会取到 13, TLE 了

 

代码

bubuko.com,布布扣
#include <iostream>
#include <stdio.h>
using namespace std;

bool chess[15][15];
int n;

int cnt;
void dfs(int depth) {
    if(depth == n) {
        cnt ++;
        return;
    }

    for(int i = 0; i < n; i ++) {

        bool qualify = true;
        for(int j = depth-1; j >= 0; j --) {
            if(chess[j][i]) {
                qualify = false;
                break;
            }
        }

        if(!qualify)
            continue;

        for(int k = 1; depth-k >= 0 && i-k >= 0; k++) {
            if(chess[depth-k][i-k]) {
                qualify = false;
                break;
            }
        }

        if(!qualify)
            continue;

        for(int k = 1; depth-k >= 0 && i+k < n; k ++) {
            if(chess[depth-k][i+k]) {
                qualify = false;
                break;
            }
        }

        if(!qualify) {
            continue;
        }

        // qualified

        chess[depth][i] = true;
        dfs(depth + 1);
        chess[depth][i] = false;
    }
}

int main() {
    while(scanf("%d", &n) != EOF) {
        cnt = 0;

        dfs(0);

        cout << cnt << endl;
    }
    return 0;
}
bubuko.com,布布扣

九度 1254:N皇后问题,布布扣,bubuko.com

九度 1254:N皇后问题

原文:http://www.cnblogs.com/xinsheng/p/3586963.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!