首页 > 代码库 > N-Queens

N-Queens

N-Queens

 Total Accepted: 12866 Total Submissions: 49759My Submissions

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.."]
]
经典的N皇后问题,这个问题采用DFS比较容易解决。
class Solution {
public:
    vector<vector<string> > solveNQueens(int n) {
        ans.clear();
        vector<string> puzzle;
        puzzle_size = n;
        for (int i = 0; i < n; ++i) {
            puzzle.push_back(string(n, '.'));
        }
        solve(puzzle, 0);
        return ans;
    }
private:
    vector<vector<string> > ans;
    int puzzle_size;
    void solve(vector<string> &puzzle, int row) {
        if (row == puzzle_size) {
            ans.push_back(puzzle);
            return;
        }
        for (int i = 0; i < puzzle_size; ++i) {
            puzzle[row][i] = 'Q';
            if (!isConflict(puzzle, row, i)) {
                solve(puzzle, row + 1);
            }
            puzzle[row][i] = '.';
        }
    }
    bool isConflict(const vector<string> &puzzle, int row, int col) {
        for (int i = row - 1; i >= 0; --i) {
            if ('Q' == puzzle[i][col]) {
                return true;
            }
            int diff_col = row - i;
            if (col - diff_col >= 0 && 'Q' == puzzle[i][col - diff_col]) {
                return true;
            }
            if (col + diff_col < puzzle_size && 'Q' == puzzle[i][col + diff_col]) {
                return true;
            }
        }
        return false;
    }
};


N-Queens