The Problem
"There's a robot in the top left corner of the grid. The robot can only move right, or down. The grid can contain invalid/blocked cells that the robot cannot step onto. Verify if there is a path to the bottom right cell in the grid from the top left."
The Solutions
I have two solutions, both of which use memoization in order to prevent re-doing the same work that you might do in a naive implementation.
Solution 1:
 1  def findPathCached( cache, grid, dstR, dstC, currentRow, currentColumn ):
 2     if currentRow > dstR or currentColumn > dstC or \
 3        grid[currentRow][currentColumn] == 1:
 4         return False
 5
 6     if currentRow == dstR and currentColumn == dstC:
 7         return True
 8
 9     if cache[currentRow][currentColumn] is None:
 10         cache[currentRow][currentColumn] = \
 11             findPathCached( cache, grid, dstR, dstC, currentRow, currentColumn+1 ) or \
 12             findPathCached( cache, grid, dstR, dstC, currentRow+1, currentColumn )
 13
 14     return cache[currentRow][currentColumn]
Solution 2:
 1 def findPathCachedFailed( cache, grid, dstR, dstC, currentRow, currentColumn ):
 2     if currentRow > dstR or currentColumn > dstC or \
 3        grid[currentRow][currentColumn] == 1:
 4         return False
 5
 6     if cache[currentRow][currentColumn]:
 7         return False
 8
 9     if ( currentRow == dstR and currentColumn == dstC ) or \
 10        findPathCachedFailed( cache, grid, dstR, dstC, currentRow, currentColumn+1 ) or \
 11        findPathCachedFailed( cache, grid, dstR, dstC, currentRow+1, currentColumn ):
 12         return True
 13
 14     cache[currentRow][currentColumn] = True
 15     return False
Solution 2 reliably runs faster than Solution 1. Doing some timing of each function call with time.time() in python, I can see over 10,000 runs the average run-time in seconds for both is:
Solution 1: 0.004197101092338562
Solution 2: 0.0036973851680755614
Running it by hand, Solution 2 very rarely takes more time than Solution 1. Both solutions are ran against the same grid.
I know the difference is small, but I had thought that Solution 1 would be better than Solution 2 since it caches every result, not just failed paths so I'm kind of surprised Solution 2 is so reliably better than 1.
Can anyone help me understand why Solution 2 is running faster?
 
     
     
     
    