Skip to content

Instantly share code, notes, and snippets.

@trykhov
Created May 15, 2020 00:59
Show Gist options
  • Save trykhov/4e0ce5ebbc9910097c718ff5b41d234f to your computer and use it in GitHub Desktop.
Save trykhov/4e0ce5ebbc9910097c718ff5b41d234f to your computer and use it in GitHub Desktop.
DFS demo code
// assuming that the input is an adjacency list
// e.g adj = {A: [B,C], B:[D,F], ... }
function dfs(adj, v, t) {
// adj is the adjacency list
// v is the node that's being visited
// t is the final destination
// these are the base cases
// either reach the destination or has already been visited
if(v === t) return true;
if(v.visited) return false;
// mark the node as visited
v.visited = true;
// explore all the neighbors of v
for(let neighbor of adj[v]) {
// if the neighbor hasn't been visited
if(!neighbor.visited) {
// go down the path & determine if t has been reached
let reached = dfs(adj, neighbor, t);
// return true if t has been reached
if(reached) return true;
}
}
// there is no path to t from v
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment