zoukankan      html  css  js  c++  java
  • LeetCode OJ-- N-Queens **

    https://oj.leetcode.com/problems/n-queens/

    n皇后问题,1皇后有1个解,4皇后2个解,8皇后也有解……

    每个皇后不能在同一行上,同一列上,以及同一条45度线上。

    可以把皇后所在位置用一维数组表示,比如 2 0 3 1,表示第0个皇后在第0行的第二个位置上……

    所以验证条件就是,不能有两个数相等,不能 位置差值 == 值的差值

    N皇后问题,使用递归法。

    对于一个皇后,它所属于列的所有位置,遍历,找出合理的位置,之后递归下一个皇后

    class Solution {
    public:
        vector<vector<string> > solveNQueens(int n) {
            vector<vector<string> >  ans;
            if(n<=0)
                return ans;
    
            vector<int> places(n,-1);
            
            placeQueen(0, n, ans, places);
            
            return ans;
        }
        
        // col and lines
        bool valid(int i, int j, vector<int> &places)
        {
            for(int p = 0; p<i; p++)
            {
                if(places[p] == j || abs(i - p) == abs(places[p] - j))
                    return false;
            }
            return true;
        }
        
        void placeQueen(int i, int n, vector<vector<string> > &ans, vector<int> &places)
        {
            // one solution
            if(i == n)
            {
                vector<string> ansPiece;
                for(int p = 0; p<n; p++)
                {
                    string str;
                    str.resize(n);
                    for(int q = 0; q<places[p]; q++)
                        str[q] = '.';
                    str[places[p]] = 'Q';
                    for(int q = places[p] + 1; q < n; q++)
                        str[q] = '.';
                    ansPiece.push_back(str);
                }
                ans.push_back(ansPiece);
            }
            
            for(int col = 0; col < n; col++)
            {
                if(valid(i,col,places))
                {
                    places[i] = col;
                    placeQueen(i+1,n,ans,places); // next queue, next line
                }
            }
        }
    };
  • 相关阅读:
    基于node.js 的 websocket的移动端H5直播开发
    c# 基于RTMP推流 PC+移动端 拉流播放
    Android Studio解决Error:moudle not specified
    能ping通域名,却不能上网
    转 Postman访问Webapi的Get/Post/Put/Delte请求
    Sqlite 参数化 模糊查询 解决方案
    autofac使用总结
    windows7 安装pytorch
    linux nginx 如何配置多个端口
    委托应用实例演变
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3876469.html
Copyright © 2011-2022 走看看