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;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章