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