educative.io

Difference of the sequence of 'visited' between BFS and DFS

Hi,
I noticed that in BFS, we mark a node visited whenever it is put into the queue, however in DFS, we mark a node only when it is popped from the stack, Is the sequence of this ‘mark’ step matters? I tried marked nodes visited in both situations and they all works fine, so is there any requirement that we must do in either way or is it just our own choice?

Hi @Junqing_Long ,

This is Fatimah Abdullah from Educative. I noticed your feedback here, and I’m glad you reached out to us.

No, the sequence of the “mark” step does not really matter unless you are marking the correct node in each iteration. Both of the shown approaches are correct and can be used. There is no strict order requirement in this case.

Best Regards,
Fatimah Abdullah | Developer Advocate
Educative Inc.