Depth First Search of Graph using Recursion

Hi there, I’m trying to use recursion to depth first search of the Unidirected Graph in Javascript. Iam using the adjacent list to store the vertices.

Here is the adjacent list and code I’ve written




  adjList: {
    A: [ 'B', 'C' ],
    B: [ 'A', 'D' ],
    C: [ 'A', 'E' ],
    D: [ 'B', 'E', 'F' ],
    E: [ 'C', 'D', 'F' ],
    F: [ 'D', 'E' ]
  }



 dfsRecursion(vertex, visited={}, vertexList=[]){
   let verter;
   if(!vertex){
     return null;
   }else{
     vertexList.push(vertex);
     visited[vertex]=true;
     for(let i=0;i<this.adjList[vertex].length;i++){
       if(!visited[this.adjList[vertex][i]]){
         return this.dfsRecursion(this.adjList[vertex][i], visited, vertexList);
       }
     }
   }return vertexList;
 }  // [ 'A', 'B', 'D', 'E', 'C' ] but expected to get  [ 'A', 'B', 'D', 'E', 'C' ,'F']

While using the recursion when I’m looping through the ‘D’ it has to wait for ‘F’ and should come back later after completion of looping the vertex ‘C’ but I didn’t understand why. Please explain and correct me If I’m wrong.

Thanks in advance.

Are you able to point in code where exactly the waiting should happen? Because result suggests that’s not really happening, taking closer look at that place might give some ideas what’s wrong.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.