zoukankan      html  css  js  c++  java
  • leetcode:N-Queens 问题

    一、N-QueensII

     1 class Solution {
     2 public:
     3     int totalNQueens(int n) {
     4         int total = 0;
     5         vector<int> v(n,0);
     6         dfs(0,n,total,v);
     7         return total;
     8     }
     9 private:
    10     bool isvalide(vector<int>& v,int x){
    11         for(int i=0;i<x;i++){
    12             if(v[i]==v[x] || abs(v[x]-v[i])==abs(x - i))
    13                 return false;
    14         }
    15         return true;
    16     }
    17 
    18     void dfs(int curr,int n,int& total,vector<int>& v){
    19         if(curr == n) {
    20             total++;
    21             return;
    22         }
    23 
    24         for(int i=0;i<n;i++){
    25             v[curr] = i;
    26             if(isvalide(v,curr)){
    27                 dfs(curr+1,n,total,v);
    28             }
    29         }
    30     }
    31 };

    二、N-Queens

     1 class Solution {
     2 public:
     3     vector<vector<string>> solveNQueens(int n) {
     4         vector<vector<string>> result;
     5         vector<int> v(n,-1);
     6         dfs(0,n,v,result);
     7         return result;
     8     }
     9     bool isValide(vector<int>& v,int curr){
    10         for(int i=0;i< curr;i++){
    11             if(v[i] == v[curr] || abs(v[curr]-v[i])==abs(curr-i))
    12                 return false;
    13         }
    14         return true;
    15     }
    16     void dfs(int curr,int n,vector<int>& v,
    17             vector<vector<string>>& result){
    18         if(curr == n){
    19             vector<string> temp;
    20             for(int i=0;i<n;i++){
    21                 string s(n,'.');
    22                 s[v[i]] = 'Q';
    23                 temp.push_back(s);
    24             }
    25             result.push_back(temp);
    26             return;
    27         }
    28         for(int i=0;i<n;i++){
    29             v[curr] = i;
    30             if(isValide(v,curr)){
    31                 dfs(curr+1, n, v,result);
    32             }
    33         }
    34     }
    35 };
  • 相关阅读:
    Grid布局方式
    布局
    应用主题资源
    主题资源
    返回键
    标记 {x:Null},d:DesignWidth,d:DesignHeight
    WMAppManifest.xml
    项目模板
    Panorama和Pivot控件
    ashx页面中context.Session["xxx"]获取不到值的解决办法
  • 原文地址:https://www.cnblogs.com/wxquare/p/4989866.html
Copyright © 2011-2022 走看看