zoukankan      html  css  js  c++  java
  • 力扣算法题—052N皇后问题2

    跟前面的N皇后问题没区别,还更简单

     1 #include "000库函数.h"
     2 
     3 //使用回溯法
     4 class Solution {
     5 public:
     6     int totalNQueens(int n) {
     7         int res = 0;
     8         vector<int>x(n, -1);//标记
     9         NQueue(x, res, 0);
    10         return res;
    11     }
    12 
    13     void NQueue(vector<int>&x, int &num, int row) {
    14         int n = x.size();
    15         if (n == row)
    16             num++;
    17         for (int col = 0; col < n; ++col) 
    18             if (Danger(x, row, col)) {
    19                 x[row] = col;
    20                 NQueue(x, num, row + 1);
    21                 x[row] = -1;//回溯
    22             }        
    23     }
    24 
    25     bool Danger(vector<int>x, int row, int col) {
    26         for (int i = 0; i < row; ++i)
    27             if (col == x[i] || abs(row - i) == abs(x[i] - col))
    28                 //行列与斜边
    29                 return false;
    30         return true;
    31     }
    32 };
    33 
    34 void T052() {
    35     Solution s;
    36     cout << s.totalNQueens(4) << endl;
    37     cout << s.totalNQueens(8) << endl;
    38 }
  • 相关阅读:
    open jdk
    llvm 编译
    llvm Array Bounds Check Elimination
    tmux 共享窗口大小
    llvm pass
    llvm code call graph
    llvm -O 经历过那些pass
    tcmalloc asan
    web ide
    eclipse配置
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10631319.html
Copyright © 2011-2022 走看看