I think there is a discrepancy in the “Understanding Graphs and Trees” theory I just want to confirm before opening an Issue.
In the “Depth-First Search (DFS)” section:
Step 2:
We pop node A from the stack.
Then, we add its unvisited children, node B and node C, to the stack. We’ll add them in reverse order,
CthenB, so thatBis on top (LIFO) and will be processed next. We also mark them as visited.
- Stack:
[C, B]- Visited:
{A, B, C}
So in step 2, B and C are both added to the “Visited” set. However, they are at the same Depth.
If we skip to the end, step 8:
- Stack:
[]- Visited:
{A, B, C, D, E, F, G}
When the stack is empty, the traversal is completed and all nodes have been visited.
The algorithm visited the nodes in this order:
A → B → D → E → C → F → G
If B and C were added to the visited set first, how to we know that D and E were visited first?
This is a problem if I’m implementing this in the Implement the Depth-First Search Algorithm lab
https://www.freecodecamp.org/learn/python-v9/lab-depth-first-search/lab-depth-first-search
If I add items to a visited list in the order described by this algorithm, the order will be {A, B, C, D, E, F, G} , not A → B → D → E → C → F → G.
I can fix this, but it just seems strange to add B and C to visited in Step 2 if C isn’t visited yet?
From the test in the lab:
- dfs([[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]], 1) should return [1, 2, 3, 0].`
Following the above algorithm, Node 1 will be added to visited, then 0 and 2 will be added. However, [1, 2, 3, 0] indicates that 0 should be visited after 3.
Am I correct the algorithm in the theory is mis-leading? Or it assumes the order of visited is tracked somewhere else and just doesn’t mention it?
EDIT: (This is all on top of the fact that a set is not the correct thing to use for the implementation since it won’t preserve order and also I noticed it sorts the numbers)