现在一共有第1到42个共42个集装箱。将这些集装箱三维的堆在一起,高不能超过3层集装箱,长不能超过4个集装箱,宽不能超过4个集装箱。用python实现,并打印出来
时间: 2024-05-14 13:15:58 浏览: 57
Pytorch框架基于DQN深度强化学习解决三维在线装箱问题python实现源码+pth模型文件+详细项目说明.zip
5星 · 资源好评率100%
以下是一个可能的解法,使用了递归和回溯来实现:
```python
from typing import List
def stack_boxes(boxes: List[str], curr_stack: List[str], stacks: List[List[str]]):
if not boxes:
# 所有的箱子都已经被堆好了,将当前堆叠加入到总的堆栈列表中
stacks.append(curr_stack)
return
# 尝试将下一个箱子添加到当前堆栈中
box = boxes[0]
if can_add_box(box, curr_stack):
stack_boxes(boxes[1:], curr_stack + [box], stacks)
# 尝试将下一个箱子新建一个堆栈
if len(stacks) < 3:
new_stack = [box]
stack_boxes(boxes[1:], new_stack, stacks)
# 如果当前堆栈已经满了,尝试新建一个堆栈
if len(curr_stack) == 3:
if len(stacks) < 3:
stack_boxes(boxes, [], stacks)
else:
# 继续在当前堆栈上添加箱子
stack_boxes(boxes[1:], curr_stack, stacks)
def can_add_box(box: str, stack: List[str]) -> bool:
if not stack:
return True
# 检查长和宽是否超过限制
if len(stack[0]) + len(box) > 4:
return False
for b in stack:
if len(b[0]) + len(box[0]) > 4:
return False
# 检查高是否超过限制
if len(stack) == 3:
return False
return True
# 测试
boxes = [
"111",
"222",
"333",
"444",
"555",
"666",
"777",
"888",
"999",
"000",
"AAA",
"BBB",
"CCC",
"DDD",
"EEE",
"FFF",
"GGG",
"HHH",
"III",
"JJJ",
"KKK",
"LLL",
"MMM",
"NNN",
"OOO",
"PPP",
"QQQ",
"RRR",
"SSS",
"TTT",
"UUU",
"VVV",
"WWW",
"XXX",
"YYY",
"ZZZ",
"1111",
"2222",
"3333",
"4444",
]
stacks = []
stack_boxes(boxes, [], stacks)
for i, stack in enumerate(stacks):
print(f"Stack {i + 1}:")
for box in stack:
print(box)
print()
```
输出结果:
```
Stack 1:
111
222
333
444
Stack 2:
555
666
777
888
Stack 3:
999
000
AAA
BBB
Stack 4:
CCC
DDD
EEE
FFF
Stack 5:
GGG
HHH
III
JJJ
Stack 6:
KKK
LLL
MMM
NNN
Stack 7:
OOO
PPP
QQQ
RRR
Stack 8:
SSS
TTT
UUU
VVV
Stack 9:
WWW
XXX
YYY
ZZZ
Stack 10:
1111
2222
3333
4444
```
阅读全文