Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
Traversing the 2D array in the N-Queens problem

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;
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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:

  • x=3, y=2
  • x=2, y=1
  • x=1, y=0

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).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda