fork download
  1. def numPaths(warehouse):
  2. MOD = 10**9 + 7
  3.  
  4. # Handle edge case for an empty grid
  5. if not warehouse or not warehouse[0]:
  6. return 0
  7.  
  8. n = len(warehouse)
  9. m = len(warehouse[0])
  10.  
  11. # If the starting or ending cell is blocked, no path is possible
  12. if warehouse[0][0] == 0 or warehouse[n-1][m-1] == 0:
  13. return 0
  14.  
  15. # Create a 1D DP array to track paths for the current row
  16. dp = [0] * m
  17. dp[0] = 1 # Start position has 1 path
  18.  
  19. for i in range(n):
  20. for j in range(m):
  21. if warehouse[i][j] == 0:
  22. # If the cell is blocked, ways to reach it drop to 0
  23. dp[j] = 0
  24. elif j > 0:
  25. # dp[j] currently holds the value from the top cell (i-1, j)
  26. # dp[j-1] holds the value from the left cell (i, j-1)
  27. dp[j] = (dp[j] + dp[j-1]) % MOD
  28.  
  29. # The last element contains the paths to the bottom-right corner
  30. return dp[m-1]
  31.  
  32. print(numPaths([[1,1,1,1],[1,1,1,1],[1,1,1,1]]))
Success #stdin #stdout 0.1s 14052KB
stdin
Standard input is empty
stdout
10