const solveNQueens = (n) => { if (n < 1) { return []; } const ret = []; getAll(n, 0, ret, []); return ret; }; const getAll = (n, row, ret, rowCol) => { if (row === n) { ret.push(buildSolution(rowCol, n)); return; } for (let col = 0; col < n; col++) { if (isValid(row, col, rowCol)) { rowCol[row] = col; getAll(n, row + 1, ret, rowCol); } } }; const isValid = (row, col, rowCol) => { for (let r = 0; r < row; r++) { if (rowCol[r] === col) { return false; } const c = rowCol[r]; if ((row - r) === Math.abs(c - col)) { return false; } } return true; }; const buildSolution = (rowCol, n) => { const ans = []; for (let i = 0; i < n; i++) { let str = ''; for (let j = 0; j < n; j++) { str += rowCol[i] === j ? 'Q' : '.'; } ans.push(str); } return ans; };
Categories