首页 > 其他 > 详细

19.2.8 [LeetCode 51] N-Queens II

时间:2019-02-08 16:48:40      阅读:153      评论:0      收藏:0      [点我收藏+]

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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
技术分享图片
 1 class Solution {
 2 public:
 3     bool valid(vector<int>&a, int x, int y) {
 4         for (int i = 0; i < x; i++)
 5             if (y == a[i] || abs(a[i] - y) == x - i)
 6                 return false;
 7         return true;
 8     }
 9     void build(int&ans,vector<int>&now,int row) {
10         int n = now.size();
11         if (row == n) 
12             ans++;
13         else {
14             for (int i = 0; i < n; i++)
15                 if (valid(now, row, i)) {
16                     now[row] = i;
17                     build(ans, now, row + 1);
18                 }
19         }
20     }
21     int totalNQueens(int n) {
22         vector<int>now(n, -1);
23         int ans = 0;
24         build(ans, now, 0);
25         return ans;
26     }
27 };
View Code

用&传送参数可以快好多,终于知道上一题为什么比别人慢了

19.2.8 [LeetCode 51] N-Queens II

原文:https://www.cnblogs.com/yalphait/p/10356335.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!