九度 1254:N皇后问题

Leetcode 原题.

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

 

代码

#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;
}

 

posted @ 2014-03-07 18:03  SangS  阅读(261)  评论(0编辑  收藏  举报