Advertisement
Guest User

Untitled

a guest
May 24th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #let A be nxn array
  2. for i in 1..n:
  3. for j in 1..n:
  4.  
  5. if i == 1:
  6. A[i][j] = c(i, j)
  7.  
  8. else:
  9. if j == 1:
  10. A[i][j] = c(i, j) + min(A[i-1][j], A[i-1][j+1])
  11. else if j == n:
  12. A[i][j] = c(i, j) + min(A[i-1][j-1], A[i-1][j])
  13. else:
  14. A[i][j] = c(i, j) + min(A[i-1][j-1], A[i-1][j], A[i-1][j+1])
  15.  
  16. # get minimum value for A[n][j]
  17. min_cost = inf
  18. min_j = None
  19. for j in 1..n:
  20. if min_cost < A[n][j]:
  21. min_cost = A[n][j]
  22. min_j = j
  23.  
  24. # minimum path-recovery
  25. min_path = [(n, min_j)]
  26. current_min_cost = min_cost - c(n, min_j)
  27.  
  28. for i in n-1..1:
  29. last_j = min_path[-1][1]
  30. if A[i][last_j] == current_min_cost:
  31. new_j = last_j
  32. else if last_j != 1 and A[i][last_j - 1] == current_min_cost:
  33. new_j = last_j - 1
  34. else:
  35. new_j = last_j + 1
  36. min_path.append((i, new_j))
  37. current_min_cost -= c(i, new_j)
  38.  
  39. # reverse since nodes were added in reversed order
  40. min_path = min_path[::-1]
  41.  
  42. # algorithm's output
  43. print min_path
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement