whilelen(queue) > 0: n, depth = len(queue), depth + 1 for i inrange(n): first = queue.pop(0) for k inrange(4): base = first // 10 ** k % 10 for d in (-1, 1): # first - base * 10 ** k -> get the base number with target digit reset to 0. # ~ + (base + d) % 10 * 10 ** k -> add back the caculated target digit. nxt = first - base * 10 ** k + (base + d) % 10 * 10 ** k if nxt == target: return depth if seen[int(nxt)]: continue seen[int(nxt)] = 1 queue.append(nxt) return -1
q, step = deque(["0000"]), -1 while q: step += 1 for _ inrange(len(q)): curr = q.popleft() if curr == target: return step if curr in visited: continue visited.add(curr) for i inrange(4): for nxt in [curr[:i] + str((int(curr[i]) + x) % 10) + curr[i + 1:] for x in (1, -1)]: if nxt notin visited: q.append(nxt)