我有一个结构如下的清单:
0 ; (0,0,G) ; []
1 ; (9,0,B) ; []
2 ; (9,9,R) ; []
3 ; (-1,-1,E) ; []
4 ; (-1,-1,E) ; []
5 ; (-1,-1,E) ; []
6 ; (-1,-1,E) ; []
7 ; (-1,-1,E) ; []
8 ; (-1,-1,E) ; []列表中的每一项都有一个索引、一个元组和一个邻居的列表,其中包含邻居的索引。
我的搜索从索引1或索引2开始,我需要从它们到索引0的所有路径。此外,我还需要一个包含路径上所有索引的列表。
我使用递归来实现这一点,并且使用一个全局可变变量(BlueChains)来存储所有可能的路径。我希望在不使用全局变量的情况下也这样做,但是我希望函数返回所有路径的列表,因为它会在代码的其他部分造成问题。
我的函数是这样的:
let rec traverseBlue index visited =
match index with
| 0 ->
let newVisited = 0 :: visited
blueChains <- newVisited :: blueChains
printfn "Golden Cog Reached! Blue wins the game!"
currentGameStatus <- WonByB
| ind ->
if not (List.contains ind visited) then
let newVisited = ind :: visited
blueChains <- newVisited :: blueChains
printfn "INDEX: %i VISITED: %A" ind newVisited
for i in tree.[ind].connectedNodes do
traverseBlue i newVisited我得到的输出是:
INDEX: 1 VISITED: [1]
INDEX: 3 VISITED: [3; 1]
BLUE CHAINS : [[1]; [1; 3]]对于蓝色链,我希望得到相同的值,但不需要使用全局变量。
发布于 2019-07-09 00:51:48
多亏@glennsl解决了我的问题,我终于做到了这一点。
let rec traverseBlue index visited oldBlueChains =
let mutable blueChains = []
match index with
| 0 ->
let newVisited = 0 :: visited
blueChains <- newVisited :: oldBlueChains
printfn "Golden Cog Reached! Blue wins the game!"
currentGameStatus <- WonByB
blueChains
| ind ->
if not (List.contains ind visited) then
let newVisited = ind :: visited
blueChains <- newVisited :: oldBlueChains
printfn "INDEX: %i VISITED: %A" ind newVisited
for i in tree.[ind].connectedNodes do
blueChains <- (traverseBlue i newVisited blueChains) @ blueChainshttps://stackoverflow.com/questions/56938033
复制相似问题