-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
62 lines (59 loc) · 1.78 KB
/
Program.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
//思路与LeetCode 51相同。使用回溯算法试着找出摆放皇后的所有方法。
using System;
using System.Collections.Generic;
namespace NQueensII
{
class Program
{
static void Main(string[] args)
{
int n = 4;
Console.WriteLine(TotalNQueens(n));
}
static int TotalNQueens(int n)
{
var board = new int[n][];
for (int i = 0; i < board.Length; i++)
board[i] = new int[n];
var res = 0;
DFS(0, n, board, ref res);
return res;
}
static void UpdateBoard(int r, int c, int n, int[][] board)
{
int[] dr = { -1, 1, 0, 0, -1, 1, -1, 1 };
int[] dc = { 0, 0, -1, 1, -1, -1, 1, 1 };
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 8; j++)
{
int newR = r + dr[j] * i;
int newC = c + dc[j] * i;
if (newR < 0 || newR >= n || newC < 0 || newC >= n) continue;
board[newR][newC] = 1;
}
}
}
static void DFS(int r, int n, int[][] board, ref int res)
{
if (r == n)
{
res++;
return;
}
for (int c = 0; c < n; c++)
{
if (board[r][c] == 1) continue;
var record = new int[n][];
for (int i = 0; i < record.Length; i++)
{
record[i] = new int[n];
Array.Copy(board[i], record[i], n);
}
UpdateBoard(r, c, n, board);
DFS(r + 1, n, board, ref res);
board = record;
}
}
}
}