forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
36 lines (34 loc) · 1019 Bytes
/
Solution.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
public class Solution {
private int n;
private int[] col;
private int[] dg;
private int[] udg;
private IList<IList<string>> ans = new List<IList<string>>();
private IList<string> t = new List<string>();
public IList<IList<string>> SolveNQueens(int n) {
this.n = n;
col = new int[n];
dg = new int[n << 1];
udg = new int[n << 1];
dfs(0);
return ans;
}
private void dfs(int i) {
if (i == n) {
ans.Add(new List<string>(t));
return;
}
for (int j = 0; j < n; ++j) {
if (col[j] + dg[i + j] + udg[n - i + j] == 0) {
char[] row = new char[n];
Array.Fill(row, '.');
row[j] = 'Q';
t.Add(new string(row));
col[j] = dg[i + j] = udg[n - i + j] = 1;
dfs(i + 1);
col[j] = dg[i + j] = udg[n - i + j] = 0;
t.RemoveAt(t.Count - 1);
}
}
}
}