LeetCode 51/52. N-Queens i, ii

1. 题目描述

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. 解题思路

这是一个非常典型的回溯问题, 使用DFS 可以处理

3. code

51

class Solution {
public:
    vector<vector<string>> solveNQueens(int n) {
        vector<string> arr(n, string(n, '.'));
        vector<vector<string>> res;
        DFS(res, arr, 0);
        return res;
    }

private:
    bool isOK(vector<string> & arr, int row, int col){
        int n = arr.size();
        for (int i = 0; i != row; i++){
            if (arr[i][col] == 'Q')
                return false;

            int col1 = col - row + i;
            if (col1 >= 0 && col1 < n && arr[i][col1] == 'Q')
                return false;

            int col2 = row + col - i;
            if (col2 >= 0 && col2 < n && arr[i][col2] == 'Q')
                return false;
        }
        return true;
    }

    void DFS(vector<vector<string>> & res, vector<string> & arr, int row){
        int n = arr.size();
        if (n == row){
            res.push_back(arr);
            return;
        }

        for (int i = 0; i != n; i++){
            if (isOK(arr, row, i)){
                arr[row][i] = 'Q';
                DFS(res, arr, row + 1);
                arr[row][i] = '.';
            }               
        }
    }
};

52

class Solution {
public:
    int totalNQueens(int n) {
        vector<string> arr(n, string(n, '.'));
        vector<vector<string>> res;
        DFS(res, arr, 0);
        return res.size();
    }

private:
    bool isOK(vector<string> & arr, int row, int col){
        int n = arr.size();
        for (int i = 0; i != row; i++){
            if (arr[i][col] == 'Q')
                return false;

            int col1 = col - row + i;
            if (col1 >= 0 && col1 < n && arr[i][col1] == 'Q')
                return false;

            int col2 = row + col - i;
            if (col2 >= 0 && col2 < n && arr[i][col2] == 'Q')
                return false;
        }
        return true;
    }

    void DFS(vector<vector<string>> & res, vector<string> & arr, int row){
        int n = arr.size();
        if (n == row){
            res.push_back(arr);
            return;
        }

        for (int i = 0; i != n; i++){
            if (isOK(arr, row, i)){
                arr[row][i] = 'Q';
                DFS(res, arr, row + 1);
                arr[row][i] = '.';
            }               
        }
    }    


};

你可能感兴趣的:(LeetCode)