0

I don’t understand why the paths printed here would be correct.

How does the path parameter not permanently get changed after child nodes are added to the path here?

For example, say I have a graph like 1 with child nodes 2 3, where 2 has child nodes 4 5.

The path upon hitting node 4 will be [1,2,4]. But, from the attached code, why isn’t the path variable still [1,2,4] before entering node 5? There’s nowhere in this code that involves a popping of nodes upon exiting. I just don’t see how the code here makes it such the path is [1,2,5]. Does the answer involve recursive stack frames?

enter image description here

Kashif
  • 3,063
  • 6
  • 29
  • 45
  • 1
    `path = path + [start]` creates a completely new list by copying, which is simply thrown away when DFS returns. If it were `path.append(start)`, your concern would be justified. This way of tracking paths needs O(n^2) storage for paths of length n. Pretty terrible. Two morals: 1) HLL's like Python make it easy to write inefficient code that still looks cool. 2) Don't trust random code snippets. – Gene Dec 22 '22 at 04:12

0 Answers0