[LintCode] N-Queens

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.

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

There exist two distinct solutions to the 4-queens puzzle:

[

    [".Q..", // Solution 1

     "...Q",

     "Q...",

     "..Q."],

    ["..Q.", // Solution 2

     "Q...",

     "...Q",

     ".Q.."]

]

 

 1 class Solution {
 2 public:
 3     /**
 4      * Get all distinct N-Queen solutions
 5      * @param n: The number of queens
 6      * @return: All distinct solutions
 7      * For example, A string '...Q' shows a queen on forth position
 8      */
 9     bool isOK(vector<string> &v, int n, int x, int y) {
10         for (int i = 0; i < x; ++i) 
11             if (v[i][y] == 'Q') return false;
12         for (int i = 1; x - i >= 0 && y - i >= 0; ++i) 
13             if (v[x-i][y-i] == 'Q') return false;
14         for (int i = 1; x - i >= 0 && y + i < n; ++i)
15             if (v[x-i][y+i] == 'Q') return false;
16         return true;
17     }
18     void dfs(vector<vector<string>> &res, vector<string> &v, int n, int idx) {
19         if (idx == n) {
20             res.push_back(v);
21             return;
22         }
23         for (int i = 0; i < n; ++i) {
24             v[idx][i] = 'Q';
25             if (isOK(v, n, idx, i)) dfs(res, v, n, idx + 1);
26             v[idx][i] = '.';
27         }
28     }
29     vector<vector<string> > solveNQueens(int n) {
30         // write your code here
31         vector<vector<string>> res;
32         string s;
33         for (int i = 0; i < n; ++i) s.push_back('.');
34         vector<string> v(n, s);
35         dfs(res, v, n, 0);
36         return res;
37     }
38 };

 

posted @ 2015-07-14 19:11  Eason Liu  阅读(333)  评论(0编辑  收藏  举报