• leetcode--N-Queens


    1.题目描述

    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,figure below
    There exist two distinct solutions to the 4-queens puzzle:

    [
    [".Q..", // Solution 1
    "...Q",
    "Q...",
    "..Q."],

    ["..Q.", // Solution 2
    "Q...",
    "...Q",
    ".Q.."]
    ]

    image

    2.解法分析

    这个是DFS的典型应用,回溯法来解这个题的代码如下:

    class Solution {
    public:
    vector<vector<string> > solveNQueens(int n) {
    // Start typing your C/C++ solution below
    // DO NOT write int main() function

    vector<vector<int> >result;
    vector<int> path;

    mySolveNQueens(result,path,n);

    //构建输出的每一项的模板,节省时间
    string line(n,'.');
    vector<string>square(n,line);
    vector<vector<string> >string_result;

    vector<vector<int> >::iterator iter;

    for(iter=result.begin();iter!=result.end();++iter)
    {
    vector<string> temp=square;
    for(int i=0;i<n;++i)
    {
    temp[i][(*iter)[i]]='Q';
    }

    string_result.push_back(temp);
    }

    return string_result;
    }

    //深度搜索,不断回溯
    void mySolveNQueens(vector<vector<int> > &result,vector<int> &path,int n)
    {
    //在当前层遍历
    for(int i=0;i<n;++i)
    {
    //如果当前层的某个位置i和之前的摆放不冲突,则加入该位置
    if(!isConflict(path,i))
    {
    path.push_back(i);
    if(path.size()==n)result.push_back(path);//找到一个解,继续
    else
    mySolveNQueens(result,path,n);//还没到最后一层,继续
    path.pop_back();//考虑该层的下一个位置,当然,得先把这个位置抹掉
    }
    }
    }

    bool isConflict(vector<int> &path,int loc)
    {
    for(int i=0;i<path.size();++i)
    {
    //在同一列或者同一斜线上为冲突
    if(path[i]==loc||((path[i]-loc)==(path.size()-i))||(path[i]-loc)==(i-path.size()))return true;
    }
    return false;
    }
    };

  • 相关阅读:
    解决docx4j 变量替换 由于变量存在样式式或空白字符 导致替换失败问题
    redis批量删除key 远程批量删除key
    idea 集成sonarLint检查代码bugs
    mac jmeter 的使用
    tomcat配置管理员-走后门
    终端mysql Operation not permitted错误解决方案
    update使用inner join
    hibernate 三种状态的转换
    数据库中间表插入乱序
    解决https证书验证不通过的问题
  • 原文地址:https://www.cnblogs.com/obama/p/3329315.html
Copyright © 2020-2023  润新知