遍历 N 皇后问题中的二维数组
我正在尝试使用回溯来解决 N-Queens 问题。 N-皇后问题的链接可以在这里找到,https://leetcode.com/problems/ n-queens/ 请访问该链接以更好地了解该问题。然而,我只是想分享我觉得很难理解的部分代码。请有人向我解释一下 //check top、//check top-left、//check-top right 是如何工作的。我发现很难理解代码的这个特定部分。
var isValid = function(board, row, col) {
const n = board.length;
// check top
for (let i = 0; i < row; i++) {
if (board[i][col] === 'Q') return false;
}
// check top-left
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] === 'Q') return false;
}
// check top-right
for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] === 'Q') return false;
}
return true;
}
I am trying to solve the N-Queens problem using backtracking. The link to the N-Queens problem can be found here, https://leetcode.com/problems/n-queens/ please visit that link for a better understanding of the problem. However, I just want to share a portion of the code I am finding hard to understand. Please can someone explain to me how the //check top, //check top - left, // check-top right works. I am finding it hard to wrap my head around this particular section of the code.
var isValid = function(board, row, col) {
const n = board.length;
// check top
for (let i = 0; i < row; i++) {
if (board[i][col] === 'Q') return false;
}
// check top-left
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] === 'Q') return false;
}
// check top-right
for (let i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
if (board[i][j] === 'Q') return false;
}
return true;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解,我们需要检查当前位置是否“安全”。所以场上没有皇后可以击中这个位置。
为此,我们需要检查垂直、水平和对角线(两者)。
此代码可能只检查当前行之上的行。
左上角的代码块执行以下操作:
想象一下,当前位置是 x=4,y=3。因此,要检查左上角对角线,我们需要查看位置:
为此,我们首先选择位置
让 i = row - 1, j = col - 1
(从当前位置向左一步和上一步)。然后,对于下一步,从上到左移动:
i--, j--
重复此操作,直到触及边界:
i >= 0 && j >= 0
右上角的块执行相同的操作,除了我们应该向右移动(增加 X)。
As far as I understand, we need to check whether the current position is "safe". So there are no Queens on the field which can hit the position.
To do so, we need to check Vertical, Horizontal, and Diagonals (both).
This code probably checks only rows above the current one.
The top-left code block does the following:
Imagine, that the current position is x=4, y=3. So to check the left-top diagonal we need to look at the positions:
To do so we initially select the position
let i = row - 1, j = col - 1
(one left and one top step from the current).And then for every next step, move top-and-left:
i--, j--
Repeat it until the border is hit:
i >= 0 && j >= 0
The top-right block performs same operation, except we should move to the right (increase the X).