你好!有一个递归函数可以找到图中的所有路径:
func (this *Graph) FindPath(from Word, to Word, visited Dict, current Path) {
if from.Eq(to) {
if len(current) > this.Max {
this.Max = len(current)
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
}
vis := make(Dict, len(visited))
copy(vis, visited)
vis = append(vis, from)
cur := make(Path, len(current))
copy(cur, current)
cur = append(cur, this.rules[r])
this.FindPath(from.ApplyRule(this.rules[r]), to, vis, cur)
}
}
我试图让它迭代:
func (this *Graph) FindPathes(from Word, to Word) {
this.Pathes = make([]Path, 0)
this.Max = 0
nodes := stack.New()
pathes := stack.New()
visiteds := stack.New()
nodes.Push(from)
visiteds.Push(Dict{from})
pathes.Push(make(Path, 0))
for nodes.Len != 0 {
curn := nodes.Pop().(Word)
curp := pathes.Pop().(Path)
curv := visiteds.Pop().(Dict)
if curn.Eq(to) {
if len(curp) > this.Max {
this.Max = len(curp)
fmt.Println(curp.ApplyVerbose(from))
}
this.Pathes = append(this.Pathes, curp)
continue
}
for r := 0; r < len(this.rules); r++ {
index := curn.Index(this.rules[r].Pat)
if index == -1 {
continue
}
newword := curn.ApplyRule(this.rules[r])
if curv.Index(newword) != -1 {
continue
}
newp := make(Path, len(curp))
copy(newp, curp)
newp = append(curp, this.rules[r])
newv := make(Dict, len(curv))
copy(newv, curv)
newv = append(newv, newword)
pathes.Push(newp)
nodes.Push(newword)
visiteds.Push(newv)
}
}
}
stack - 堆栈的自写实现,假设一切都在那里正常工作。
单词-[]int
字典-[]Word
路径-[]Rule
规则-struct{Pat Word, Rep Word}
Index - 用于Dict并Path返回所需元素的索引(或 -1),以及 for Word- 子字符串开始的位置(或 -1)。
Word.Eq - 检查两个单词是否相等。
第一个函数正常工作,但第二个函数没有在合理的时间内完成。你可以帮帮我吗?
在第一段代码中有一行:
第二个没有类似的东西。有必要
newword在声明后添加相同的条件:现在一切正常。重要的一点:迭代函数至少快三倍。