HJ77_火车进站_栈_递归_递归可视化

发布时间 2023-04-08 12:32:52作者: Aneverforget

思路:

多维递归模拟进站出站,递归回溯,使用全局变量收集结果,最后输出结果。

语言知识:

1、关于参数传入和可变变量修改

 

2、错误使用return

 

 

3、进出站不同跟踪方法。cursor只是表示等待进站火车下标。

 

 

 

递归可视化:

 

 

 

 

 程序:

 1 import sys
 2 a=sys.stdin.readline()
 3 wait=sys.stdin.readline().strip().split()
 4 cursor=0#等待进站火车号下标
 5 stack,out=[],[]
 6 #t=out.append(wait[cursor])
 7 #t1=stack.pop()
 8 s=[]
 9 def trainO(cursor,stack,out):
10     #print("0",cursor)
11     if wait[-1] in stack:
12         #收集火车出站列表        
13         s.append(out+stack[::-1 ])
14         return
15     if stack==[]:
16         #print("1" )
17         #火车进站
18         trainO(cursor+1,stack+[wait[cursor]],out)
19     else:
20         #print("2")
21         #火车进站
22         trainO(cursor+1,stack+[wait[cursor]],out)
23         #print("3",stack,out)
24         #火车出站
25         trainO(cursor,stack[:-1],out+[stack[-1]])
26 trainO(cursor,stack,out)
27 s=sorted(s)
28 for i in s:
29     print(" ".join(i))