leetcode99:n-queens

题目描述

N皇后问题是把N个皇后放在一个N×N棋盘上,使皇后之间不会互相攻击。

给出一个整数n,返回n皇后问题的所有摆放方案
例如:
4皇后问题有两种摆放方案
[".Q..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
]


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..",  // 解法 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // 解法 2
  "Q...",
  "...Q",
  ".Q.."]
class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        vector <vector<string>> res;
        vector<string> cur(n,string(n,'.'));
        dfs(res,cur,n,0);
        return res;
    }
    
    void dfs(vector <vector<string>> &res,vector <string> &cur,int &n,int row){
        if (row==n){
            res.push_back(cur);
            return ;
        }
        
        for (int j=0;j<n;j++){
            if (isValid (cur,n,row,j)){
                cur[row][j]='Q';
                dfs(res,cur,n,row+1);
                cur[row][j]='.';
            }
        }
    }
    
    bool isValid(vector<string> &cur,int &n ,int row,int col){
        for (int i=0;i<row;i++){
            if (cur[i][col]=='Q'){
                return false;
            }
        }
        
        for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--){
            if (cur[i][j]=='Q'){
                return false;
            }
        }
        
        for (int i=row-1,j=col+1;i>=0 && j<n;i--,j++){
            if (cur[i][j]=='Q'){
                return false;
            }
                
        }
    
    return true;
    }
};


posted on 2020-07-31 08:43  滚雪球效应  阅读(125)  评论(0编辑  收藏  举报