Depth first search: return values
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
01:34 Accepted answer (Score 0)
02:04 Answer 2 (Score 4)
03:01 Answer 3 (Score 0)
03:39 Thank you
--
Full question
https://stackoverflow.com/questions/2129...
Question links:
[here]: http://jeremykun.com/2013/01/22/depth-an.../
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #algorithm #recursion #depthfirstsearch
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
01:34 Accepted answer (Score 0)
02:04 Answer 2 (Score 4)
03:01 Answer 3 (Score 0)
03:39 Thank you
--
Full question
https://stackoverflow.com/questions/2129...
Question links:
[here]: http://jeremykun.com/2013/01/22/depth-an.../
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #algorithm #recursion #depthfirstsearch
#avk47
ANSWER 1
Score 4
Suppose we have the following graph:
1 ——— 2
|
4 ——— 5 ——— 6
| | |
7 ——— 8 ——— 9
Where soughtValue is node 9. Starting from node 1 as source:
wrong code:
===========
dfs(1,9,…) dfs(2,9,…)
… …
// neighbors // neighbors
return dfs(2,9,…) <———| NO return dfs(1,9,…) as 1 has been visited
return dfs(4,9,…) |
|
| so return false
| |
|-------------|
result
dfs(1,9,…) terminates with a false even without going to dfs(4,9,…)
correct code:
============
dfs(1,9,…) dfs(2,9,…)
… …
// neighbors // neighbors
if (dfs(2,9,…)) <———| NO if dfs(1,9,…) as as 1 has been visited
return true | return true
|
if (dfs(4,9,…)) |
return true |
|
| so return false
| |
|-------------|
result
dfs(1,9,…) doesn't terminate and does continue to other neighbors (i.e., dfs(4,9,…)) and so on until we reach the soughtValue 9 and return true
ACCEPTED ANSWER
Score 0
We can't return any value, because if it's False, the for loop breaks and never finds the True that may be later..
Example:
def divisible_by_five_A():
for n in range(100):
if n and not n % 5:
return n, 1
divisible_by_five_A()
# O: 5, 1
vs
def divisible_by_five_B():
for n in range(100):
return n, (n and not n % 5)
divisible_by_five_B()
# O: 0, 0
ANSWER 3
Score 0
Yes, the search needs to continue if depthFirst(adjNode, soughtValue, visitedNodes) returns False. Only when you've found the sought value in that part of the graph then you can return True for your search.
If you were to replace that with return depthFirst(adjNode, soughtValue, visitedNodes) then you'll only search for the value in that part of the graph (starting from that adjacent node) but you won't continue your search in case the value isn't found there.