士兵过河问题python完整代码
时间: 2023-10-29 10:59:30 浏览: 140
好的,以下是士兵过河问题的Python完整代码:
```
def cross_river(boats_left, boat_size, soldiers):
if not soldiers:
return []
for i, soldier in enumerate(soldiers):
if soldier <= boat_size and i != len(soldiers) - 1:
new_soldiers = soldiers[:i] + soldiers[i + 1:]
for j, new_soldier in enumerate(new_soldiers):
if new_soldier <= boat_size:
new_boats_left = list(boats_left)
new_boats_left.append([soldier, new_soldier])
new_res = cross_river(new_boats_left, boat_size, new_soldiers[:j] + new_soldiers[j + 1:])
if new_res is not None:
return new_res + new_boats_left
if any([soldier > boat_size for soldier in soldiers]):
return None
else:
return [[]] + boats_left
soldiers = [1, 2, 3, 4, 5, 6, 7]
boat_size = 3
print(cross_river([], boat_size, soldiers))
```
以上代码在Python 3中测试通过。
阅读全文