zoukankan      html  css  js  c++  java
  • 51. N-Queens 52. N-Queens II *HARD*

    1. 求所有解

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

    Given an integer n, return all distinct solutions to the n-queens puzzle.

    Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]
    void insert(vector<vector<string>> &ans, vector<int> q, int n)
    {
        vector<string> v(n, string(n, '.'));
        for(int i = 0; i < n; i++)
            v[i][q[i]] = 'Q';
        ans.push_back(v);
    }
    void helper(vector<vector<string>> &ans, vector<int> q, int n, int k)
    {
        if(k == n)
        {
            insert(ans, q, n);
            return;
        }
        int i, j;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < k; j++)
            {
                if(q[j] == i || abs(j-k) == abs(q[j]-i))
                    break;
            }
            if(j < k)
                continue;
            q[k] = i;
            helper(ans, q, n, k+1);
        }
    }
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> ans;
        vector<int> q(n, -1);
        for(int i = 0; i < n; i++)
        {
            q[0] = i;
            helper(ans, q, n, 1);
        }
        return ans;
    }

    2. 求解的个数

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    void helper(int &ans, vector<int> q, int n, int k)
    {
        if(k == n)
        {
            ans++;
            return;
        }
        int i, j;
        for(i = 0; i < n; i++)
        {
            for(j = 0; j < k; j++)
            {
                if(q[j] == i || abs(j-k) == abs(q[j]-i))
                    break;
            }
            if(j < k)
                continue;
            q[k] = i;
            helper(ans, q, n, k+1);
        }
    }
    int totalNQueens(int n) {
        int ans = 0;
        vector<int> q(n, -1);
        for(int i = 0; i < n; i++)
        {
            q[0] = i;
            helper(ans, q, n, 1);
        }
        return ans;
  • 相关阅读:
    洛谷 P3868 [TJOI2009]猜数字
    洛谷 P2661 信息传递
    hdu 5418 Victor and World
    洛谷 P5024 保卫王国
    洛谷 P2470 [SCOI2007]压缩
    双栈排序 2008年NOIP全国联赛提高组(二分图染色)
    理想的正方形 HAOI2007(二维RMQ)
    10.23NOIP模拟题
    疫情控制 2012年NOIP全国联赛提高组(二分答案+贪心)
    图论模板
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5265909.html
Copyright © 2011-2022 走看看