zoukankan      html  css  js  c++  java
  • LeetCode51 N-Queens

    题目:

    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. (Hard)

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

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

    分析:

    n皇后问题,典型的搜索思路,对每一行,依次遍历选择一个位置,添加一个Q进去,判断是否合法。合法则处理下一行,不合法则回退到上一行选择其他位置添加Q。

    注意isVaild函数的写法,行在添加过程中保证不重复,列需要判断,主副对角线通过x + y为定值和 x - y为定值判断(注意均只需要判断x,y之前的即添加过的部分)。

    代码:

     1 class Solution {
     2 private:
     3     vector<vector<string>> result;
     4     void helper(vector<string>& v, int row, int n) {
     5         for (int i = 0; i < n; ++i) {
     6             v[row][i] = 'Q';
     7             if (isValid(v, row, i, n)) {
     8                 if (row == n - 1) {
     9                     result.push_back(v);
    10                     v[row][i] = '.';
    11                     return;
    12                 }
    13                 helper(v, row + 1, n);
    14             }
    15             v[row][i] = '.';
    16         }
    17     }
    18     bool isValid (const vector<string>& v, int x, int y, int n) {
    19         for (int i = 0; i < x; ++i) {
    20             if (v[i][y] == 'Q') {
    21                 return false;
    22             }
    23         }
    24         for(int i = x - 1, j = y - 1; i >= 0 && j >= 0; i--,j--) {
    25             if(v[i][j] == 'Q') {
    26                 return false;
    27             }
    28         }
    29         for(int i = x - 1, j = y + 1; i >= 0 && j < n; i--,j++){
    30             if(v[i][j] == 'Q') {
    31                 return false;
    32             }
    33         }
    34         return true;
    35     }
    36 public:
    37     vector<vector<string>> solveNQueens(int n) {
    38         vector<string> v(n, string(n, '.'));
    39         helper(v,0,n);
    40         return result;
    41     }
    42 };
  • 相关阅读:
    sci会议和sci期刊区别是什么
    微信小程序保存图片到相册
    详解python3如何调用c语言代码
    微信小程序的跳转navigateTo()和redirectTo()用法和区别
    python+opencv图像变换的两种方法cv2.warpAffine和cv2.warpPerspective
    微信小程序
    微信小程序不同机型的兼容布局解决
    cv2.warpAffine 参数详解
    np.vstack()和np.hstack()
    numpy.linalg.svd函数
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5854735.html
Copyright © 2011-2022 走看看