码迷,mamicode.com
首页 > 其他好文 > 详细

N-Queens

时间:2014-08-24 22:21:03      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   io   for   ar   问题   div   

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.

bubuko.com,布布扣

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

标签:style   http   color   os   io   for   ar   问题   div   

原文地址:http://blog.csdn.net/freeliao/article/details/38799383

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!