-1

I'm trying to implement a depth first search algorithm for a graph data structure and my function looks like this:

void dfs(int x, vector <v_Int>& Adjacency_List, v_Int& visited) {
    visited[x] = 1; //Mark current vertex as visited
     for (int i = 0; i < Adjacency_List[x].size(); i++) { //Iterate through all neighbours of vertex x
        if (visited[i] != 1) { //If neighbour not visited, recursively go there
            dfs(i, Adjacency_List, visited);
        }
    }
}

When I used a normal for loop like I did above, the visited array does not get updated beyond the first vertex of the graph when I call the function dfs(0, Adjacency_List, visited);

However, when I change the normal for loop to a range based for loop like so:

    for (auto &v : Adjacency_List[x]) { //Iterate through all neighbours of vertex x
        if (!visited[v]) {
            dfs(v, Adjacency_List, visited); //If neighbour not visited, recursively go there
        }
    }

The visited array gets updated accordingly whenever the dfs function is called. I'm not too sure why the 2nd implementation works but my initial implementation doesn't since both implementations seem to have similar logics. Thank you for your help!

Edit: v_Int is a typedef I declared to be a vector of integers

  • 3
    You replaced `i` with `v`, but `v` is actually equivalent to `Adjacency_List[x][i]`. – HolyBlackCat Apr 04 '21 at 14:17
  • What is `v_Int`? `visited[v]` indexes a `v_Int` with another `v_Int` which I'm surprised manages to compile. – interjay Apr 04 '21 at 14:18
  • The two loops are completely different. The first one uses the `i` as an index, a value from 0 to `size()-1`. The range loop uses the actual values in the `visited` array. VTC as a typo. – Sam Varshavchik Apr 04 '21 at 14:18

1 Answers1

1

In first implementation, neighbour is not i, its Adjacency_List[x][i].

int neighbour = Adjacency_List[x][i];
if (visited[neighbour] != 1) { //If neighbour not visited, recursively go there
    dfs(neighbour, Adjacency_List, visited);
}
Rana Vivek
  • 126
  • 2