forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
N-Queens_II.cpp
61 lines (58 loc) · 1.08 KB
/
N-Queens_II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: Jul 8, 2012
Problem: N-Queens II
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of
distinct solutions.
Solution:
dfs
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
int result;
int *board;
public:
bool feasible(int x, int y, int n) {
for (int i = 0; i < x; i++) {
if (board[i] == y || board[i] + x - i == y
|| board[i] - x + i == y) {
return false;
}
}
return true;
}
void dfs(int dep, int n) {
if (dep == n) {
result++;
return;
}
for (int i = 0; i < n; i++) {
if (feasible(dep, i, n)) {
board[dep] = i;
dfs(dep + 1, n);
board[dep] = -1;
}
}
}
int totalNQueens(int n) {
board = new int[n];
for (int i = 0; i < n; i++) {
board[i] = -1;
}
result = 0;
dfs(0, n);
return result;
}
};