LeetCode: N Queens Solution
1/**2 * @param {number} n3 * @return {string[][]}4 */5var solveNQueens = function (n) {6 const grid = Array.from({ length: n }, _ => Array(n).fill(0))7 const res = []89 const validate = (row, col) => {10 for (let i = 0; i < row; i++) {11 for (let j = 0; j < n; j++) {12 if (13 grid[i][j] &&14 (col === j || Math.abs(col - j) === Math.abs(row - i))15 ) {16 return false17 }18 }19 }20 return true21 }2223 const recursion = row => {24 if (row === n) {25 res.push(grid.map(row => row.map(col => (col ? "Q" : ".")).join("")))26 return27 }2829 for (let col = 0; col < n; col++) {30 if (validate(row, col)) {31 grid[row][col] = 132 recursion(row + 1)33 grid[row][col] = 034 }35 }36 }3738 recursion(0)3940 return res41}
Comments
Loading comments...
Tags
leetcode
recursion
backtracking
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.