This is a problem I was asked to solve during an interview, but the code I implemented during interview cannot pass all test cases, the problem is just as title said, given N and T (T >= N), which are initial floor and target floor respectively, one can move to current floor + 1, current floor - 1 or 2 * current floor in one minute, what's the minimum time need to reach the target? I think it's a typical DP problem, this is how I did in interview
@lru_cache(None)
def solve(cur):
if cur >= target: return cur - target
if cur * 2 >= target:
# if current floor * 2 < target, we can move to current floor + 1 each time or move backward to (target + 1) // 2 and move current floor * 2 next time, and if target is odd, we need extra 1 move
return min(target - cur, cur - (target + 1) // 2 + 1 + (target % 2))
return min(solve(cur + 1), solve(cur * 2)) + 1
I test it with some cases, it seems to work, I cannot figure out why it cannot pass all test cases during interview,
Update---------------------------------------------------------------
I tried using Dijkstra to solve this, but the code become a bit of mess, than I thought if the problem askes to find shortest distance, maybe we can use BFS, and I think it's the right solution, so below is the code
def solve():
while(True):
N, T = map(int, input().split())
q = deque([N])
vis = [False] * (T * 2)
vis[N] = True
steps = 0
while q:
for _ in range(len(q)):
u = q.popleft()
if u == T:
print(f'reach target in {steps} minutes')
break
cand = [u - 1, u + 1, u * 2] if u < T else [u - 1]
for v in cand:
if v > 0 and not vis[v]:
vis[v] = True
q.append(v)
steps += 1