leetcode--N-Queens

来源:互联网 发布:php vendor文件夹 编辑:程序博客网 时间:2024/06/03 06:55

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

]


解题思路:本题的解法为回溯法。回溯法的基本思想是:确定了解空间的组织结构后,回溯法就从开始节点(根节点)

出发,以深度优先的方式搜索整个解空间。这个开始节点就成为一个活节点,同时也成为当前的扩展节点。

在当前的扩展节点处,搜索向纵深方向移至一个新节点。这个新节点就成为一个新的活节点,并成为当前扩展节点。

如果当前的节点处不能再向纵深方向移动,则当前扩展节点就成为死结点。此时,应该回溯至最近的一个活结点处,并使这个活结点成为扩展结点。回溯法即采用这种递归的方式在解空间搜索,知道找到所有的解或解空间中没有活结点为止。


回溯法解题的三个步骤:

1)定义解空间

2)确定易于搜索的解空间结构

3)以深度优先的方式搜索解空间,并且在搜索过程中用剪枝函数避免无效搜索;


void traceback(int t){if(t>num)   output(x);else{for(int i=下界;i<=上界;i++){x[i]=h(i);if(constraints(t)&&bound(t))backtrace(t);}}}

回溯法搜索解空间树时,通常采用两种策略避免无效搜索,提高效率;

1)约束函数:在扩展节点处减去不满足约束的子树;

2)限界函数:减去得不到最优解的子树

class Solution {public:    vector<string> tmp;    vector<vector<string>> res;    int num;    int x[100];    int constraints(int i)//约束条件:1)不能再同一行或同一列2)两点斜率不能为正负1    {        for(int j=1;j<i;j++)            if(abs(x[j]-x[i])==abs(j-i)||x[j]==x[i])                return 0;                        return 1;    }    void traceback(int t)    {        if(t>num)        {            tmp.clear();            for(int i=1;i<=num;i++)            {                string s(num,'.');                s[x[i]-1]='Q';                tmp.push_back(s);            }                        res.push_back(tmp);                    }        else        {            for(int i=1;i<=num;i++){                x[t]=i;                        if(constraints(t))                traceback(t+1);            }        }    }    vector<vector<string> > solveNQueens(int n) {        num=n;        for(int i=0;i<100;i++)            x[i]=0;        res.clear();                     traceback(1);                  return res;    }};








0 0