-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0051-n-queens.ts
62 lines (51 loc) · 2.16 KB
/
0051-n-queens.ts
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
//check if current state is valid
const isStateValid = (state: number[], n: number) => {
//if there are n queens inserted the state is valid
return state.length === n;
};
//convert given state(valid) to correct answer format(a string)
const stateToString = (state: number[]) => {
let arrs = state.map((col) => {
let newArr = new Array(state.length).fill('.');
newArr[col] = 'Q';
return newArr.join('');
});
return arrs;
};
//recursive step
const searchRec = (state: number[], n: number, solutions: string[][]) => {
//if current state is valid, add it to the solutions array and return, we go back to previous states (DFS)
if (isStateValid(state, n)) return solutions.push(stateToString(state));
//get new possible candidates (the column in which to place current queen) to add to current State, start with every column
let candidates = new Set([...Array(n).keys()]);
//the row in which next queen will be added
let rowToAdd = state.length;
//iterates previous not empty rows to discard candidates before exploring them
for (let row = 0; row < state.length; row++) {
//the column in which is placed the queen at current row
let col = state[row];
let dist = rowToAdd - row;
//discard the whole column where queen inserte in "row" is
candidates.delete(col);
//right diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here)
candidates.delete(col + dist);
//left diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here)
candidates.delete(col - dist);
}
candidates.forEach((cand) => {
//temporarly add candidate to state
state.push(cand);
//explore new state with that candidate
searchRec(state, n, solutions);
//explored, remove the candidate to return at previous state
state.pop();
});
return;
};
function solveNQueens(n: number): string[][] {
let solutions = [];
let start = [];
//explore starting from empty state
searchRec(start, n, solutions);
return solutions;
}