题解 | #N皇后问题#

N皇后问题

https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6?tpId=295&tqId=1008753&ru=%2Fpractice%2Ffe6b651b66ae47d7acce78ffdd9a96c7&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D295

第二次做,还是不能流畅做出来。

针对每一列进行防止判断,使用递归进行下一层(行)放置

class Solution {
  public:
    /**
     * 
     * @param n int整型 the n
     * @return int整型
     */
  //  每一行只放置一个,所以可以建立行与列之间的映射关系
    int Nqueen(int n) {
      int res = 0;
      std::vector<int> pos(n, -1);
      
      recursion(n, pos, res, 0);
      
      return res;
    }
  private:
  // row的有效范围为 0 ~ n-1
    void recursion(const int &n, std::vector<int> &pos, int &res, int row) {
      if (row == n) {
        ++res;
        return ;
      }
      //  针对每一列判断
      //  递归增加行数
      for (int i = 0; i < n; ++i) {
        if (able_push(pos, row, i)) {
          pos[row] = i;
          recursion(n, pos, res, row + 1);
        } 
      }
    }
  
  bool able_push(const std::vector<int> &pos, int row, int col) {
    //  对已经放置过的每一行遍历,查找是否能放置
    for (int i = 0; i < row; ++i) {
      if (pos[i] == col || std::abs(i - row) == std::abs(pos[i] - col)) {
        return false;
      }
    }
    
    return true;
  }
};
全部评论
一维数组,每次回溯都会覆盖旧值
点赞 回复 分享
发布于 2022-07-05 11:09

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务