【leetcode】 N-Queens II

地址

https://leetcode.com/problems/n-queens-ii/description/

题目

Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. 'one solution to the eight queens puzzle'

思路

和前一道一摸一样的暴力题

代码

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
class Solution {
public:
int n,ul[100],ux[100],uy[100],ans=0;
char mp[100][100];

void dfs(int x)
{
if(x==n)
{
ans++;
return ;
}
for(int j=0;j<n;j++)
if(ul[j]==0&&ux[j-x+50]==0&&uy[n-x-j+50]==0)
{
ul[j]=ux[j-x+50]=uy[n-x-j+50]=1;
dfs(x+1);
ul[j]=ux[j-x+50]=uy[n-x-j+50]=0;
}
}
int totalNQueens(int N) {
n=N;
memset(ul,0,sizeof ul);
memset(ux,0,sizeof ux);
memset(uy,0,sizeof uy);
dfs(0);
return ans;
}
};