LeetCode 51. N-Queens

来源:互联网 发布:java实现rsa算法 编辑:程序博客网 时间:2024/05/17 22:07

描述

n皇后问题

解决

递归,回溯


class Solution {public:vector<vector<string>> solveNQueens(int n) {    vector<vector<string>> res;    vector<string> str(n, string(n, '.'));    function<void(int, int)> rec = [&](int n, int now_pos)    {        if (now_pos == n)        {            res.push_back(str);            return ;        }        for (int i = 0; i < n; ++i)        {            bool flag = true;            for (int j = now_pos - 1; j >= 0; --j)            {            //因为斜率为1,故由横向的变化,可以算出对应的纵向的变化,由此得到了左上和右上的位置                if (str[j][i] == 'Q' || ((i - (now_pos - j)) >= 0 && str[j][i - (now_pos - j)] == 'Q') || (i + now_pos - j < n && str[j][i + now_pos- j] == 'Q'))                {                        flag = false;                        break;                }            }            if (flag)            {                str[now_pos][i] = 'Q';                rec(n, now_pos + 1);                str[now_pos][i] = '.';            }        }    };    rec(n, 0);    return res;}};
0 0
原创粉丝点击