# LeetCode: N Queens Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**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 = []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 false17        }18      }19    }20    return true21  }22
23  const recursion = row => {24    if (row === n) {25      res.push(grid.map(row => row.map(col => (col ? "Q" : ".")).join("")))26      return27    }28
29    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  }37
38  recursion(0)39
40  return res41}```

leetcode

recursion

backtracking

## Next Post

LeetCode: To Lower Case

May 25, 2021

Search Posts