zoukankan      html  css  js  c++  java
  • LeetCode 51. N-Queens

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

    image

    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.."]
    ]
    

    典型的N皇后问题, 直接暴搜就可以了。

    class Solution
    {
        void dfs(vector<vector<string>> &ans, vector<string> &mp, vector<bool> &mk_col, vector<bool> &mk_l, vector<bool> &mk_r, int x, int &n)
        {
            if(x == n)
            {
                ans.push_back(mp);
                return ;
            }
            for(int i=0; i<n; ++ i)
            {
                if(mk_col[i] == false && mk_l[x-i+n] == false && mk_r[x+i] == false)
                {
                    mp[x][i] = 'Q', mk_col[i] = true, mk_l[x-i+n] = true, mk_r[x+i] = true;
                    dfs(ans, mp, mk_col, mk_l, mk_r, x+1, n);
                    mp[x][i] = '.', mk_col[i] = false, mk_l[x-i+n] = false, mk_r[x+i] = false;
                }
            }
        }
    public:
        vector<vector<string>> solveNQueens(int n)
        {
            vector<vector<string>> ans;
            vector<string> mp(n, string(n, '.'));
            vector<bool> mk_col(n, false), mk_l(n<<1, false), mk_r(n<<1, false);
    
            dfs(ans, mp, mk_col, mk_l, mk_r, 0, n);
    
            return ans;
        }
    };
    
  • 相关阅读:
    佛學概要十四講表
    冰川时代4中英台词全集
    Linux Mysql 每天定时备份
    zabbix拓扑图
    搭建zabbix 3.4
    ★日常工作保养电脑及设备★
    宽带突然断网了,需要做如下应急措施
    预防这几点,可以让你的电脑长久耐用!!!!
    搭建简易的 DISCUZ论坛
    format 的常见用法
  • 原文地址:https://www.cnblogs.com/aiterator/p/6666533.html
Copyright © 2011-2022 走看看