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

N-Queens

时间:2014-08-27 00:11:56      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   io   for   ar   div   

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.."]
]

思路:使用DFS求解即可。在某行放置皇后时,检查所在列、对角线、反对角线是否已经放置了皇后。

 1 class Solution {
 2 public:
 3     vector<vector<string>> solveNQueens( int n ) {
 4         vector<string> solution( n, string( n, . ) );
 5         SolveSub( solution, 0, n );
 6         return solutions;
 7     }
 8 private:
 9     void SolveSub( vector<string>& solution, int step, const int &n ) {
10         if( step == n ) { solutions.push_back( solution ); return; }
11         for( int i = 0; i < n; ++i ) {
12             bool used = false;
13             for( int k = step-1; k >= 0; --k ) {
14                 if( solution[k][i] == Q ) { used = true; break; }
15             }
16             if( used ) { continue; }
17             for( int k = 1; k <= min( i, step ); ++k ) {
18                 if( solution[step-k][i-k] == Q ) { used = true; break; }
19             }
20             if( used ) { continue; }
21             for( int k = 1; k <= min( n-i, step ); ++k ) {
22                 if( solution[step-k][i+k] == Q ) { used = true; break; }
23             }
24             if( used ) { continue; }
25             solution[step][i] = Q;
26             SolveSub( solution, step+1, n );
27             solution[step][i] = .;
28         }
29         return;
30     }
31     vector<vector<string>> solutions;
32 };

 

N-Queens

标签:style   blog   http   color   使用   io   for   ar   div   

原文地址:http://www.cnblogs.com/moderate-fish/p/3938311.html

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