1 回答

TA貢獻1789條經驗 獲得超8個贊
由于您的系譜圖中可以有循環,因此您可能會陷入這樣的循環。這意味著您必須檢測循環并停止在那里構建。你可以通過稍微改變你的樹來做到這一點。
首先,您tree按值傳遞對象,但附加指向它的指針。將指針傳遞給周圍的樹:
func walk(t *tree, written map[int]int, writer io.Writer) *tree {
}
更好的方法可能是:
func (t *tree) walk(written map[int]int, writer io.Writer) {...}
您還應該將 a 添加*parent到樹中,以便檢測循環:
type tree struct {
parent *tree
sire *tree
dam *tree
animal int
base int
path []int
}
每次創建新關卡時,適當設置父級:
myTree := newTree(t.sire.animal, pedigree[t.sire.animal][0], pedigree[t.dam.animal][1], t.base)
myTree.parent=t
myTree.walk(written, writer)
然后添加一個函數來測試你是否進入循環:
func (t *tree) loop(animal int) bool {
for t!=nil {
if t.animal==animal {
return true
}
t=t.parent
}
return false
}
并檢查您是否正在進入循環:
if !myTree.loop(myTree.animal) {
myTree.walk(written, writer)
}
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報