LeetCode: N Queens Solution

1/**
2 * @param {number} n
3 * @return {string[][]}
4 */
5var solveNQueens = function (n) {
6 const grid = Array.from({ length: n }, _ => Array(n).fill(0))
7 const res = []
8
9 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 false
17 }
18 }
19 }
20 return true
21 }
22
23 const recursion = row => {
24 if (row === n) {
25 res.push(grid.map(row => row.map(col => (col ? "Q" : ".")).join("")))
26 return
27 }
28
29 for (let col = 0; col < n; col++) {
30 if (validate(row, col)) {
31 grid[row][col] = 1
32 recursion(row + 1)
33 grid[row][col] = 0
34 }
35 }
36 }
37
38 recursion(0)
39
40 return res
41}

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.

Next Post

LeetCode: To Lower Case

HoningJS

Search Posts