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

115
Visualizações
Remove nodes with dead end from path taken by Depth first search

If I console.log visited nodes, I get a ton of spare nodes that I don't want.

I just what the nodes necessary to get for start to end node (does not need to be the shortest), But I don't want all the other paths/nodes the algo took before it found the right path

function dfs(start, visited = new Set()) {

    console.log(start)
    
    visited.add(start);

    const destinations = adjacencyList.get(start);

    for (const destination of destinations) {

        if (destination === 'BKK') { 
            console.log(`DFS found Bangkok`)
            return;
        }
        
        if (!visited.has(destination)) {
            dfs(destination, visited);
        }

    }

}

dfs('PHX')
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The idea here is to track if the node destination you visited leads to correct path or not. Hence, you should return after exhausting a particular node whether end node can be visited through this node or not.

function dfs(start, visited = new Set()) {
    visited.add(start);

    const destinations = adjacencyList.get(start);
    var result = false;
    
    for (const destination of destinations) {
        
        if (destination === 'BKK') { 
            console.log(`DFS found Bangkok`);
            console.log(destination);
            return true;
        }
        
        if (!visited.has(destination)) {
             result |= dfs(destination, visited); // you can visit end from this node
        }

    }

    if(result) {
      console.log(start);
    }

    return result;
}

dfs('PHX')

Notice that this will print nodes from start -> finish in reverse order i.e. from finish to start.
To have path from start ..->..finish, you can store in some array(instead of console.log) and reverse that after dfs is complete.

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