-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path052-NQueens2.cs
49 lines (43 loc) · 1.32 KB
/
052-NQueens2.cs
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
//-----------------------------------------------------------------------------
// Runtime: 52ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _052_NQueens2
{
public int TotalNQueens(int n)
{
int result = 0;
var queenColumns = new int[n];
RecursiveSolver(n, 0, queenColumns, ref result);
return result;
}
void RecursiveSolver(int n, int currentRow, int[] queenColumns, ref int result)
{
if (currentRow == n)
{
result++;
return;
}
bool isValid = true;
for (int col = 0; col < n; col++)
{
isValid = true;
for (int i = 0; i < currentRow; i++)
{
if (queenColumns[i] == col || Math.Abs(col - queenColumns[i]) == Math.Abs(currentRow - i))
{
isValid = false;
break;
}
}
if (!isValid) continue;
queenColumns[currentRow] = col;
RecursiveSolver(n, currentRow + 1, queenColumns, ref result);
}
}
}
}