fork(1) download
  1. # Answer for https://stackoverflow.com/questions/65445073/number-of-ways-to-bottom-right-of-matrix-with-obstacles-with-any-size-skips-righ
  2.  
  3. rows = 4
  4. cols = 3
  5.  
  6. matrix = """
  7. ...
  8. .*.
  9. ...
  10. ...
  11. """
  12.  
  13. M = [list(r) for r in matrix.split()]
  14. print(M)
  15.  
  16. #(num_ways_here, cumulative_from_north, cumulative_from_east)
  17. one = [None] * cols
  18. two = [None] * cols
  19.  
  20. for i, r in enumerate(M):
  21. for j, c in enumerate(r):
  22. if (0, 0) == (i, j):
  23. two[j] = (1, 1, 1)
  24. elif M[i][j] == "*":
  25. two[j] = (0, 0, 0)
  26. elif i == 0:
  27. (c, n, e) = two[j-1]
  28. curr = e
  29. two[j] = (e, curr, e + curr)
  30. elif j == 0:
  31. (c, n, e) = one[j]
  32. curr = n
  33. two[j] = (curr, n + curr, curr)
  34. else:
  35. (cw, nw, ew) = two[j-1]
  36. (cn, nn, en) = one[j]
  37. curr = ew + nn
  38. two[j] = (curr, nn + curr, ew + curr)
  39. one = two
  40. two = [None] * cols
  41. print(one)
  42.  
  43. print(one[cols-1][0])
Success #stdin #stdout 0.03s 9152KB
stdin
Standard input is empty
stdout
[['.', '.', '.'], ['.', '*', '.'], ['.', '.', '.'], ['.', '.', '.']]
[(1, 1, 1), (1, 1, 2), (2, 2, 4)]
[(1, 2, 1), (0, 0, 0), (2, 4, 2)]
[(2, 4, 2), (2, 2, 4), (8, 12, 12)]
[(4, 8, 4), (6, 8, 10), (22, 34, 32)]
22