zoukankan      html  css  js  c++  java
  • N皇后问题

    N皇后问题
    Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
    Submit Status

    Description

    在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。 
    你的任务是,对于给定的N,求出有多少种合法的放置方法。 

     

    Input

    共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
     

    Output

    共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
     

    Sample Input

    
    
    1 8 5 0
     

    Sample Output

    
    
    1 92 10

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    #include<iostream>
    using namespace std;


    const int N = 12;
    int area[12];
    int ans;
    int n;


    void DFS(int m) {
        if (m == n) {
            ans++;
            return ;
        }
        for (int i = 0; i < n; i++) {
            area[m] = i;
            bool ok = true;
            for (int j = 0; j < m; j++) {
                if (area[m] == area[j] || (m - area[m]) == (j - area[j]) || (m + area[m]) == (j + area[j])) {
                    ok = false;
                    break;
                }
            }
            if (ok) DFS(m + 1);
        }
    }


    int main() {
        int rec[11];
        for (int i = 1; i <= 10; i++) {
            memset(area, 0, sizeof(area));
            ans = 0;
            n = i;
            DFS(0);
            rec[i] = ans;
        }
        while (cin>>n) {
            if (!n) break;
            cout<<rec[n]<<endl;
        }
        return 0;
    }

  • 相关阅读:
    深度学习
    !gcc !vi
    条件、循环及其他语句
    当索引行不通时
    我的排班日期
    Linux使用storcli工具查看服务器硬盘和raid组信息
    storcli64和smartctl定位硬盘的故障信息
    Shell-四剑客
    iostat
    /VAR/LOG/各个日志文件分析
  • 原文地址:https://www.cnblogs.com/steamedbun/p/9373460.html
Copyright © 2011-2022 走看看