|
| 1 | +//check if current state is valid |
| 2 | +const isStateValid = (state: number[], n: number) => { |
| 3 | + //if there are n queens inserted the state is valid |
| 4 | + return state.length === n; |
| 5 | +}; |
| 6 | + |
| 7 | +//convert given state(valid) to correct answer format(a string) |
| 8 | +const stateToString = (state: number[]) => { |
| 9 | + let arrs = state.map((col) => { |
| 10 | + let newArr = new Array(state.length).fill('.'); |
| 11 | + newArr[col] = 'Q'; |
| 12 | + return newArr.join(''); |
| 13 | + }); |
| 14 | + |
| 15 | + return arrs; |
| 16 | +}; |
| 17 | + |
| 18 | +//recursive step |
| 19 | +const searchRec = (state: number[], n: number, solutions: string[][]) => { |
| 20 | + //if current state is valid, add it to the solutions array and return, we go back to previous states (DFS) |
| 21 | + if (isStateValid(state, n)) return solutions.push(stateToString(state)); |
| 22 | + |
| 23 | + //get new possible candidates (the column in which to place current queen) to add to current State, start with every column |
| 24 | + let candidates = new Set([...Array(n).keys()]); |
| 25 | + |
| 26 | + //the row in which next queen will be added |
| 27 | + let rowToAdd = state.length; |
| 28 | + |
| 29 | + //iterates previous not empty rows to discard candidates before exploring them |
| 30 | + for (let row = 0; row < state.length; row++) { |
| 31 | + //the column in which is placed the queen at current row |
| 32 | + let col = state[row]; |
| 33 | + let dist = rowToAdd - row; |
| 34 | + //discard the whole column where queen inserte in "row" is |
| 35 | + candidates.delete(col); |
| 36 | + //right diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) |
| 37 | + candidates.delete(col + dist); |
| 38 | + //left diagonal intersection of queen inserted in "row" with the row where to add new queen(new queen cannot be here) |
| 39 | + candidates.delete(col - dist); |
| 40 | + } |
| 41 | + |
| 42 | + candidates.forEach((cand) => { |
| 43 | + //temporarly add candidate to state |
| 44 | + state.push(cand); |
| 45 | + //explore new state with that candidate |
| 46 | + searchRec(state, n, solutions); |
| 47 | + //explored, remove the candidate to return at previous state |
| 48 | + state.pop(); |
| 49 | + }); |
| 50 | + |
| 51 | + return; |
| 52 | +}; |
| 53 | + |
| 54 | +function solveNQueens(n: number): string[][] { |
| 55 | + let solutions = []; |
| 56 | + let start = []; |
| 57 | + |
| 58 | + //explore starting from empty state |
| 59 | + searchRec(start, n, solutions); |
| 60 | + |
| 61 | + return solutions; |
| 62 | +} |
0 commit comments