跳转至

51.N-Queens

Tags: Hard Depth-first Search Backtracking

Links: https://leetcode.com/problems/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.

img

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.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

class Solution {
    vector<vector<string>> res;
    vector<int> d;
public:
    vector<vector<string>> solveNQueens(int n) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        d.resize(n, 0);
        DFS(0, n);

        return res;
    }

    void DFS(int row, int n)
    {
        for (int col = 0; col < n; ++col) {
            if (canPlace(row, col)) {
                d[row] = col;

                if (row == n - 1) {
                    vector<string> tmp(n, string(n, '.'));
                    for (int i = 0; i < n; ++i) {
                        int j = d[i];
                        tmp[i][j] = 'Q';
                    }
                    res.push_back(tmp);
                }
                else DFS(row + 1, n);
            }
        }
    }

    bool canPlace(int row, int col)
    {
        for (int i = 0; i < row; ++i) {
            if (d[i] == col || abs(i - row) == abs(d[i] - col)) 
                return false;
        }
        return true;
    }
};