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

leetcode 51. N-Queens

时间:2015-03-08 15:31:44      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

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.."]
]
[solution]
 1 vector<vector<string> > result;
 2     vector<vector<string> > solveNQueens(int n) 
 3     {
 4         if (n <= 0)
 5             return result;
 6         vector<int> mark(n, 0);
 7         
 8         NQueen(mark, n, 0);
 9         return result;
10     }
11     
12     void NQueen(vector<int> &mark, int n, int row)
13     {
14         if (row == n) // get a solution
15         {
16             vector<string> strRow;
17             for (int i = 0; i < n; i++)
18             {
19                 string str;
20                 for (int j = 0; j < n; j++)
21                     if (mark[i] == j)
22                         str.push_back(Q);
23                     else
24                         str.push_back(.);
25                 strRow.push_back(str);
26             }
27             result.push_back(strRow);
28             return;
29         }
30         
31         for (int i = 0; i < n; i++)
32         {
33             mark[row] = i;
34             if (check(mark, row))
35                 NQueen(mark, n, row + 1);
36         }
37     }
38     
39     bool check(vector<int> mark, int row)
40     {
41         for (int i = 0; i < row; i++)
42         {
43             if (mark[i] == mark[row] || abs(mark[i] - mark[row]) == (row - i))
44                 return false;
45         }
46         return true;
47     }

 

leetcode 51. N-Queens

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4321663.html

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