What is the difference between for/of and forEach in the depth-first search (DFS) of a graph?

107 Views Asked by At

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"));
1

There are 1 best solutions below

0
On

Your for...of loop doesn't give the correct result because the return causes it to break out of the loop prematurely. You can fix it by removing the return:

for(const ele of adjacencyList[v]){
    if(!obj[ele]) helper(ele);
}

Explanation from Mozilla Developer Network (MDN):

In for...of loops, abrupt iteration termination can be caused by break, throw or return. In these cases, the iterator is closed.

(Source: for...of article, "Closing iterators" section)