We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
出处:LeetCode 算法第52题 n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。 上图为 8 皇后问题的一种解法。 给定一个整数 n,返回 n 皇后不同的解决方案的数量。 示例: 输入: 4 输出: 2 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..", // 解法 1 "...Q", "Q...", "..Q."], ["..Q.", // 解法 2 "Q...", "...Q", ".Q.."] ]
出处:LeetCode 算法第52题
n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击。
上图为 8 皇后问题的一种解法。
给定一个整数 n,返回 n 皇后不同的解决方案的数量。
示例:
输入: 4 输出: 2 解释: 4 皇后问题存在如下两个不同的解法。 [ [".Q..", // 解法 1 "...Q", "Q...", "..Q."], ["..Q.", // 解法 2 "Q...", "...Q", ".Q.."] ]
采用回溯法,遍历所有的可能性,输出结果
function isSafe(array, n, x, y) { for (var i = 0; i < n; i++) { for (var j = 0; j < y; j++) { if (array[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i)) { return false; } } } return true; } function solve(array, col, result, n) { if (col == n) { var temp = []; for (var i = 0; i < n; i++) { temp.push(array[i].join('')); } result.push(temp); return; } for (var i = 0; i < n; i++) { if (isSafe(array, n, i, col)) { array[i][col] = 'Q'; solve(array, col + 1, result, n); array[i][col] = '.' } } } var totalNQueens = function (n) { var result = []; var array = []; for (var i = 0; i < n; i++) { array[i] = []; for (var j = 0; j < n; j++) { array[i][j] = '.'; } } solve(array, 0, result, n); return result.length; }; console.log(totalNQueens(4));
The text was updated successfully, but these errors were encountered:
No branches or pull requests
习题
思路
采用回溯法,遍历所有的可能性,输出结果
解答
The text was updated successfully, but these errors were encountered: