基本上这是一个简单的搜索问题,你的状态是乌龟当前位置的元组和它的速度。它可以在不使用堆栈(深度优先)或队列(广度优先搜索)的情况下实现。这是在 Python 中使用队列的实现,即广度优先:
from collections import deque
def cross_river(river, position=0, speed=1):
queue = deque([(position, speed, [])])
visited = set()
while queue:
position, speed, path = queue.popleft()
# if last stone of river, return sequence of jumps to get there
if position == len(river) - 1:
return path
# check whether we've been here before
if (position, abs(speed)) in visited:
continue
visited.add((position, abs(speed)))
# for all possible jumps, add the new state to the queue
for i in [-1, 0, +1]: # change in speed
for k in [-1, +1]: # change in direction
new_spd = (speed + i) * k
new_pos = position + new_spd
if 0 <= new_pos < len(river) and river[new_pos] == 1:
queue.append((new_pos, new_spd, path + [new_spd]))
print cross_river([1,0,1,1,0,0,0,1,1,0,1]) # Result: [2, -2, 3, 4, 3]
(事实上,这个算法比你的问题中描述的更严格,因为乌龟必须准确地落在最后一块石头上,而不是另一边的任何地方,但这应该很容易改变。)