你好!有一个图,其中节点是单词(类型Word),边缘是将一个单词转换为另一个单词的替换。
例如:节点123和之间333有一条边12->33。
有一种方法可以查找从一个单词到另一个单词的所有路径并将它们存储在this.Path中:
func (this *Graph) FindPath(from Word, to Word, visited Dict, current Path) {
if from.Eq(to) {
if len(this.Pathes) == 0 {
fmt.Println(current)
}
this.Pathes = append(this.Pathes, current)
return
}
if visited.Index(from) != -1 { // если уже были в этом узле
return
}
index := this.nodes.Index(from)
if index == -1 {
return
}
for r := 0; r < len(this.rules); r++ {
index := from.Index(this.rules[r].Pat)
if index == -1 {
continue
}
this.FindPath(from.ApplyRule(this.rules[r]), to, append(visited, from), append(current, this.rules[r]))
}
return
}
此方法完成后,this.Path将包含有效和无效路径。将此行添加到main:
fmt.Println(g.Pathes[0])
并与FindPath方法的第 4 行的输出进行比较。我们得到:
[{[1 0 1] [0]} {[0] [1]} {[1] [1 0]} {[1 0] [1 1]}] // FindPath, правильный путь
[{[1 0 1] [0]} {[0] [1]} {[1] [1 0]} {[1 0] [1 1 1]}] // main
你可以帮帮我吗?我可以发布更多代码,但在我看来,错误就在这里。
在这里它循环运行
append。假设,起初,在一个切片中有一些东西: (1)[a, b, c]。然后添加了一些东西: (2)[a, b, c, d]。然后他们尝试添加其他内容: (3)[a, b, c, e]。但是第二步中的切片和第三步必须存放在同一个地方,所以第一个被第二个代替。你需要这样做:
同时,我还没有想出一个清楚说明这一点的例子。如果有人提供一个十行的程序,我将不胜感激,这将毫不含糊地遵循。
翻译