4 ms·
It doesn't stop at 1 because the previous function call (dfs(19)) hasn't finished processing its neighbor list yet. If you're wondering "how does it know that"
by tgflynn 5y ago
It doesn't stop at 1 because the previous function call (dfs(19)) hasn't finished processing its neighbor list yet. If you're wondering "how does it know that" it's because each function call creates a stack frame to keep track of its state (ie. arguments, temporary variables, etc.). When a function call returns the stack frame of its caller is essentially restored.
Recursion can be a tough concept to grasp the first time you encounter it (and sometimes even for a while after that).
I would suggest that you work with a simpler recursive function (dfs is a somewhat advanced example), like, for example, factorial until you understand exactly what's going on. Use print statements to see when each function call happens, when it returns and what its arguments are. Secondly you should try to find a ressource that explains how function calls and stack frames work. I don't know of any off the top of my head but I'm sure if you do some Googling you'll find what you need.