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;
  • 相关阅读:
    Maven3核心技术(笔记三)
    解决Ubuntu下Sublime Text 3无法输入中文
    python3项目之数据可视化
    Python模块Pygame安装
    PHP命名空间(Namespace)
    git的安装使用和代码自动部署
    input:text 的value 和 attribute('value') 不是一回事
    touch事件学习
    获得 选中文字
    linux使用crontab实现PHP执行定时任务及codeiginter参数传递相关
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5265909.html
Copyright © 2011-2022 走看看