51. N-Queens

Problem statement:

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

Solution:

As a classical, N-Queens typically is a DFS problem. The solution follows DFS template. 

According to the rules to place the queen, they can not in the same column, we do not need to keep a vector which records if a position is visited or not. 

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<vector<string>> solu_sets;
        vector<string> solu(n, string(n, '.'));
        NQueens(solu_sets, solu, 0, n, n);
        return solu_sets;
    }
private:
    void NQueens(vector<vector<string>>& solu_sets, vector<string>& solu, int row, int col, int n){
        if(row == n){
            solu_sets.push_back(solu);
            return;
        }
        for(int i = 0; i < col; i++){
            if(isvalid(solu, row, i, n)){
                solu[row][i] = 'Q';
                NQueens(solu_sets, solu, row + 1, col, n);
                solu[row][i] = '.';
            }
        }
        return;
    }
    bool isvalid(vector<string>& solu, int row, int col, int n){
        for(int i = row - 1, left = col - 1, right = col + 1; i >= 0; i--, left--, right++){
            // vertically/diagonal/anti-diagonal conflict
            if(solu[i][col] == 'Q' || (left >= 0 && solu[i][left] == 'Q') || (right < n && solu[i][right] == 'Q')){
                return false;
            }
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/wdw828/p/6839305.html