Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!