Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning recursive function vs. returning variable that stores value of recursive function

These two functions are returning different results. They look identical to me. What is going on here?

def DFS(r, c, grid):
   if (r<0 or r>=len(grid) or c<0 or c>=len(grid[0])):
      return False
   if (grid[r][c] == 1):
      return True
      
      grid[r][c]=1
      return DFS(r+1, c, grid) and DFS(r-1, c, grid) and DFS(r, c+1, grid) and DFS(r, c-1, grid)

and

def DFS(r, c, grid):
   if (r<0 or r>=len(grid) or c<0 or c>=len(grid[0])):
      return False
   if (grid[r][c] == 1):
      return True
   grid[r][c] = 1

   down = DFS(r+1, c, grid)
   up = DFS(r-1, c, grid)
   right = DFS(r, c+1, grid)
   left = DFS(r, c-1, grid)
   return down and up and right and left

For example in this code block,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for r in range(len(grid)):
            for c in range(len(grid[0])):
                if (grid[r][c] == 0):
                    #print("searching", r, c)
                    if (DFS(r, c, grid) == True):
                        print([r,c])
                        result+=1
        return result

The two DFS functions will return different values when given this input:

[[0,0,1,1,0,1,0,0,1,0],[1,1,0,1,1,0,1,1,1,0],[1,0,1,1,1,0,0,1,1,0],[0,1,1,0,0,0,0,1,0,1],[0,0,0,0,0,0,1,1,1,0],[0,1,0,1,0,1,0,1,1,1],[1,0,1,0,1,1,0,0,0,1],[1,1,1,1,1,1,0,0,0,0],[1,1,1,0,0,1,0,1,0,1],[1,1,1,0,1,1,0,1,1,0]]

Thank you for your help!

>Solution :

The first version evaluates the last 4 calls to DFS using short-circuit evaluation: i.e., if the first DFS call in the return statement returns a falsey value, the and operator won’t even bother evaluating the next 3 DFS calls.

The last version explicitly evaluates all 4 DFS calls first, and only then evaluates the 4-way and.

I’m guessing that has an impact on how often and when the grid[r][c] = 1 line is executed, which would explain why they behave differently.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading