zoukankan      html  css  js  c++  java
  • HDU 2553 N皇后问题(DFS)


    **链接 : ** Here!

    **思路 : ** 最经典的DFS问题, 思路搜索每一行 $x$, 看看有那些列能合理放置, $(x, y)$ 如果是合法点则放置, 然后搜索下一行, 如果已经合法放置了 $N$ 个点, 则方案数 $+1$ , 然后回溯 (回溯就是把之前放置的点拿起来, 可以这样理解QAQ吧...)


    /*************************************************************************
    	> File Name: E.cpp
    	> Author: 
    	> Mail: 
    	> Created Time: 2017年11月26日 星期日 10时51分05秒
     ************************************************************************/
    
    #include <iostream>
    #include <cstring>
    #include <cstdio>
    using namespace std;
    
    #define MAX_N 11
    typedef long long ll;
    ll ans[20];
    int vis1[MAX_N * 3], vis2[MAX_N * 3], vis3[MAX_N * 3];
    int n;
    
    bool check(int x, int y) {
        return (!vis1[x + y] && !vis2[y - x + n] && !vis3[y]);
    }
    void setPoint(int x, int y) {
        vis1[x + y] = vis2[y - x + n] = vis3[y] = 1;
    }
    void movePoint(int x, int y) {
        vis1[x + y] = vis2[y - x + n] = vis3[y] = 0;
    }
    int dfs(int x, int cnt, int n) {
        if (cnt == n) {
            return 1;
        }
        int total_num = 0;
        for (int j = 0 ; j < n ; ++j) {
            if (!check(x, j)) continue;
            setPoint(x, j);
            total_num += dfs(x + 1, cnt + 1, n);
            movePoint(x, j);
        }
        return total_num;
    }
    int solve(int x) {
        memset(vis1, 0, sizeof(vis1));
        memset(vis2, 0, sizeof(vis2));
        memset(vis3, 0, sizeof(vis3));
        return dfs(0, 0, x);
    }
    void init() {
        for (int i = 1 ; i < MAX_N ; ++i) {
            ans[i] = solve(i);
        }
    }
    int main() {
        init();
        while (scanf("%d", &n) != EOF) {
            if (n == 0) break;
            printf("%lld
    ", ans[n]);
        }
        return 0;
    }
    
  • 相关阅读:
    HDU 1261 字串数(排列组合)
    Codeforces 488C Fight the Monster
    HDU 1237 简单计算器
    POJ 2240 Arbitrage
    POJ 3660 Cow Contest
    POJ 1052 MPI Maelstrom
    POJ 3259 Wormholes
    POJ 3268 Silver Cow Party
    Codesforces 485D Maximum Value
    POJ 2253 Frogger(最短路)
  • 原文地址:https://www.cnblogs.com/WArobot/p/7902780.html
Copyright © 2011-2022 走看看