-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path51. N-Queens.c
124 lines (103 loc) · 2.93 KB
/
51. N-Queens.c
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
51. N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
*/
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
#define IDX(I, J, SZ) ((I) * (SZ) + J)
void set_flags(int *buff, int i, int j, int n, int flag) {
int k, x, y;
buff[IDX(i, j, n)] = flag;
for (k = 0; k < n; k ++) { // row
if (k != j && buff[IDX(i, k, n)] != -1) {
buff[IDX(i, k, n)] += flag ? 1 : -1;
}
}
for (k = 0; k < n; k ++) { // col
if (k != i && buff[IDX(k, j, n)] != -1) {
buff[IDX(k, j, n)] += flag ? 1 : -1;
}
x = k;
y = j - i + k;
if (y >= 0 && y < n) {
if (x != i && y != j && buff[IDX(x, y, n)] != -1) {
buff[IDX(x, y, n)] += flag ? 1 : -1;
}
}
y = j + i - k;
if (y >= 0 && y < n) {
if (x != i && y != j && buff[IDX(x, y, n)] != -1) {
buff[IDX(x, y, n)] += flag ? 1 : -1;
}
}
}
}
void bt(int n, char ****pp, int *psz, int *pn, int *buff, int row) {
int i, j, col, k;
if (row == n) {
// all done
if (*psz == *pn) {
*psz *= 2;
(*pp) = realloc(*pp, *psz * sizeof(char **));
//assert(*pp);
}
(*pp)[*pn] = malloc(n * sizeof(char *));
for (i = 0; i < n; i ++) {
(*pp)[*pn][i] = malloc((n + 1) * sizeof(char));
//assert((*pp)[*pn][i]);
for (j = 0; j < n; j ++) {
(*pp)[*pn][i][j] = buff[IDX(i, j, n)] == -1 ? 'Q' : '.';
}
(*pp)[*pn][i][j] = 0;
}
(*pn) ++;
return;
}
for (col = 0; col < n; col ++) {
if (buff[IDX(row, col, n)] == 0) {
set_flags(buff, row, col, n, -1);
bt(n, pp, psz, pn, buff, row + 1);
set_flags(buff, row, col, n, 0);
}
}
}
char*** solveNQueens(int n, int* returnSize) {
char ***p;
int *buff;
int psz;
psz = 10;
p = malloc(psz * sizeof(char **));
buff = calloc(n * n, sizeof(int));
//assert(result && buff);
*returnSize = 0;
bt(n, &p, &psz, returnSize, buff, 0);
free(buff);
if (!*returnSize) {
free(p);
p = NULL;
}
return p;
}
/*
Difficulty:Hard
Total Accepted:82.6K
Total Submissions:266.2K
Related Topics Backtracking
Similar Questions N-Queens II
*/