I am learning graph and in the dfs_recursion()
, when I tried to use
for(const ele of adjacencyList[v]){
if(!obj[ele]) return helper(ele);
}
instead of
adjacencyList[v].forEach(neighbor => {
if(!obj[neighbor]){
return helper(neighbor);
}
})
Why the result (graphTraversal.dfs_recursion("A")
) is different?
The first one is [ 'A', 'B', 'D', 'E', 'C' ]
The second one is [ 'A', 'B', 'D', 'E', 'C', 'F' ]
(correct answer).
I searched the difference between for...of
and forEach()
on the Internet, but still did not get the point. Can someone explain it to me?
My original code is here below:
// Build an undirected graph
class Graph {
constructor(){
this.adjacencyList = {};
}
addVertex(vtx) {
if(!this.adjacencyList[vtx]) this.adjacencyList[vtx] = [];
return this.adjacencyList;
}
addEdge(v1, v2){
if(!(this.adjacencyList.hasOwnProperty(v1) && this.adjacencyList.hasOwnProperty(v2))) return "sorry but there is no vertex";
else{
this.adjacencyList[v1].push(v2);
this.adjacencyList[v2].push(v1);
}
}
dfs_recursion(vtx){
const arr = [], obj = {};
const adjacencyList = this.adjacencyList;
const helper = (v) => {
if(!v) return null;
arr.push(v);
obj[v] = true;
adjacencyList[v].forEach(neighbor => {
if(!obj[neighbor]){
return helper(neighbor);
}
})
}
helper(vtx);
return arr;
}
}
let graphTraversal = new Graph();
graphTraversal.addVertex("A");
graphTraversal.addVertex("B");
graphTraversal.addVertex("C");
graphTraversal.addVertex("D");
graphTraversal.addVertex("E");
graphTraversal.addVertex("F");
graphTraversal.addEdge("A", "B");
graphTraversal.addEdge("A", "C");
graphTraversal.addEdge("B", "D");
graphTraversal.addEdge("C", "E");
graphTraversal.addEdge("D", "E");
graphTraversal.addEdge("D", "F");
graphTraversal.addEdge("E", "F");
console.log(graphTraversal.dfs_recursion("A"));
Your
for...of
loop doesn't give the correct result because thereturn
causes it to break out of the loop prematurely. You can fix it by removing thereturn
:Explanation from Mozilla Developer Network (MDN):