2017.11.8 LeetCode N皇后问题

来源:互联网 发布:php编程是什么 编辑:程序博客网 时间:2024/06/06 03:55
  • 前两天课多,也在学搜索这一块,终于把N皇后问题给彻彻底底的搞懂了

51. N-Queens

Description

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

题意: 很清楚,就是N皇后问题

分析: 这个呢就是dfs的一个经典运用了,的确悟到了不少知识,这段时间得加紧做点搜索的题,简单说下N皇后问题吧,首先按列搜索,每列只可能放一个皇后,然后枚举可以放的点,path记录下皇后的位置,例如path[1] = 2;就是在第一列,第二行的位置放皇后,最麻烦的就是怎样存储状态,来判断能不能放皇后,我这里呢设置了三个数组来表示,一个h数组,就是行数组,h[1] = true 表示第一行不能放了, 还有一个z数组,表示斜率为正的斜线,我们知道一个n*n的方格中存在2*n-1个斜线,我们可以找到规律为只要斜率为正的,线上的每个点都存在 index+i为定值,所以我们就可以利用这个定值来记录斜线的状态,而斜率为负的时候,同理我们可以用index-i为定值,因为数组里面不能为负数,所以我们可以同时都加上个值,使之为正的即可我这里取的是n,还是看代码吧

参考函数

class Solution {public:    vector<vector< string > > res;    bool h[100],z[100],f[100];    int path[100];    void dfs(int index,int n) {        if(index == n) {            vector<string> t;            string s;            for(int i = 0;i < n;i++) {                for(int j = 0;j < n;j++) {                    if(j == path[i]) s += "Q";                    else s += ".";                }                t.push_back(s);                s.clear();            }            res.push_back(t);        }        for(int i = 0;i < n;i++) {            path[index] = i;            if(!h[i] && !z[index+i] && !f[index-i+n]) {                h[i] = true;                z[index+i] = true;                f[index-i+n] = true;                dfs(index+1,n);                h[i] = false;                z[index+i] = false;                f[index-i+n] = false;            }        }    }    vector<vector<string>> solveNQueens(int n) {        res.clear();        dfs(0,n);        return res;    }};

52. N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

题意:求n皇后存在的种类数

分析:同51题,只是记录下种类而已

参考函数

class Solution {public:    int res;    bool h[100],z[100],f[100];    int path[100];    void dfs(int index,int n) {        if(index == n) {            res++;        }        for(int i = 0;i < n;i++) {            path[index] = i;            if(!h[i] && !z[index+i] && !f[index-i+n]) {                h[i] = true;                z[index+i] = true;                f[index-i+n] = true;                dfs(index+1,n);                h[i] = false;                z[index+i] = false;                f[index-i+n] = false;            }        }    }    int totalNQueens(int n) {        dfs(0,n);        return res;    }};