-
Notifications
You must be signed in to change notification settings - Fork 115
/
051-NQueens.cs
63 lines (55 loc) · 1.84 KB
/
051-NQueens.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//-----------------------------------------------------------------------------
// Runtime: 396ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode
{
public class _051_NQueens
{
public IList<IList<string>> SolveNQueens(int n)
{
CONST_RESULT = new string('.', n);
var results = new List<IList<string>>();
var queenColumns = new int[n];
RecursiveSolver(n, 0, queenColumns, results);
return results;
}
string CONST_RESULT;
void RecursiveSolver(int n, int currentRow, int[] queenColumns, IList<IList<string>> results)
{
if (currentRow == n)
{
var result = new List<string>();
StringBuilder rowString;
for (int i = 0; i < n; i++)
{
rowString = new StringBuilder(CONST_RESULT, n);
rowString[queenColumns[i]] = 'Q';
result.Add(rowString.ToString());
}
results.Add(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, results);
}
}
}
}