zoukankan      html  css  js  c++  java
  • [LeetCode] 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.

    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.."]
    ]
    
    用2个栈stack模拟递归bfs方法,发现stack比递归速度快很多,递归的方法在9皇后时速度特别慢,通不过,用stack就会Accept!
    class Solution {
    public:
       vector<vector<string> > result;
    
        vector<vector<string> > solveNQueens(int n) {
            vector<int> board(n+1,0);
            stack<vector<int> > s;
            s.push(board);        
            return  totalN(n,s);
    
        }
    private:
        vector<vector<string> > totalN(int n,stack<vector<int> > s){
            
            int k = 1;
            while(k<=n){
                stack<vector<int> > s0;
                while(!s.empty()){
                    vector<int> board = s.top();
                    vector<int>  board0(board);
                    s.pop();
    
                    for(int i=1;i<=n;i++){
                        board[k]=i;
                        if(isok(k,board)){
                            s0.push(board);    
                        }
                        board = board0;
                    }
    
                }
                k++;
                s = s0;
            }
    
            while(!s.empty()){
                string s0(n,'.');
                vector<string> vs(n,s0);
                vector<int> board = s.top();
                s.pop();
                for(int i=1;i<=n;i++){
                    vs[i-1][board[i]-1]='Q';
                }
                result.push_back(vs);
            }
            return result;
        }
        bool isok(int k,vector<int> &board){//check whether the ktn Queen can be put down
            for(int i=1;i<k;i++){
                if(board[i]==board[k]||abs(i-k)==abs(board[i]-board[k]))
                    return false;
            }
            return true;
        }
    };
  • 相关阅读:
    MySQL中文显示乱码
    mysql 存储引擎 InnoDB 与 MyISAM 的区别和选择
    mysql 分表的3种方法
    mysql 清空或删除表数据后,控制表自增列值的方法
    MySQL 下优化SQL语句的一些经验
    mysql 常用命令
    MySQL获得指定数据表中auto_increment自增id值的方法及实例
    SQL Server Alwayson创建代理作业注意事项
    LinkedList子类与Queue接口
    List接口
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3926401.html
Copyright © 2011-2022 走看看