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

【N-Queens】cpp

时间:2015-05-27 11:45:43      阅读:126      评论: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.."]
]

代码:

class Solution {
public:
        static vector<vector<string> > solveNQueens(int n)
        {
            vector<vector<string> > ret;
            if ( n==0 ) return ret;
            vector<string> tmp;
            vector<bool> colUsed(n,false);
            vector<bool> diagUsed1(2*n-1,false);
            vector<bool> diagUsed2(2*n-1,false);
            Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
            return ret;
        }
        static void dfs( 
            vector<vector<string> >& ret, 
            vector<string>& tmp, 
            int n,  
            vector<bool>& colUsed,
            vector<bool>& diagUsed1,
            vector<bool>& diagUsed2 )
        {
            const int row = tmp.size();
            if ( row==n )
            {
                ret.push_back(tmp);
                return;
            }
            string curr(n,.);
            for ( size_t col = 0; col<n; ++col )
            {
                if ( !colUsed[col] && !diagUsed1[col+n-1-row] && !diagUsed2[col+row] )
                {
                    colUsed[col] = !colUsed[col];
                    diagUsed1[col+n-1-row] = !diagUsed1[col+n-1-row];
                    diagUsed2[col+row] = !diagUsed2[col+row];
                    curr[col] = Q;
                    tmp.push_back(curr);
                    Solution::dfs(ret, tmp, n, colUsed, diagUsed1, diagUsed2);
                    tmp.pop_back();
                    curr[col] = .;
                    diagUsed2[col+row] = !diagUsed2[col+row];
                    diagUsed1[col+n-1-row] = !diagUsed1[col+n-1-row];
                    colUsed[col] = !colUsed[col];
                }
            }
        }
};

tips:

深搜写法:

1. 找到一个解的条件是tmp的长度等于n

2. 在一列中遍历每个位置,是否能够放置Q,并继续dfs;返回结果后,回溯tmp之前的状态,继续dfs。

一开始遗漏了对角线也不能在有超过一个Q的条件,补上之后就AC了。

【N-Queens】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4532922.html

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