I am trying to implement a DFS and I do not understand the difference between calling a function inside itself (recursion) and returning the function call (also recursion?)
Snippet 1: Returning a function call (Wrong answer)
In this case, the code is not backtracking correctly.
const graph = {
1: [2, 3],
2: [4, 5],
3: [1],
4: [2, 6],
5: [2, 6],
6: [4, 5]
}
let visited = [];
const dfs = (node) => {
if (visited.includes(node))
return;
console.log(node);
visited.push(node);
for (let i = 0; i < graph[node].length; i++) {
if (!visited.includes(graph[node][i]))
return dfs(graph[node][i])
}
}
dfs(1);
Snippet 2: Only calling the function (Correct answer)
Seems to work okay
const graph = {
1: [2, 3],
2: [4, 5],
3: [1],
4: [2, 6],
5: [2, 6],
6: [4, 5]
}
let visited = [];
const dfs = (node) => {
if (visited.includes(node))
return;
console.log(node);
visited.push(node);
for (let i = 0; i < graph[node].length; i++) {
if (!visited.includes(graph[node][i]))
dfs(graph[node][i])
}
}
dfs(1);
What is the difference between the two? (I thought they'd be the same)
Is this some language specific (JS) thing or am I misunderstanding recursion?