我正在尝试将切片作为参数传递给递归函数。由于切片作为参考传递,我相信我传递给它的递归函数应该能够毫无问题地执行操作。我只使用 append() ,因此不应该对容量不足的切片有问题吗?
package main
import "fmt"
func allPossiblePaths(arrGraph [8][8]bool, src int, dest int) [][]int {
var visited []bool //a slice that marks if visited
var path []int //a slice to store a possible path
var paths [][]int //a slice to store all paths
visited = make([]bool, 8) //set all nodes to unvisited
dfs(arrGraph, src, dest, visited, path, paths)
return paths
}
func dfs(myGraph [8][8]bool, src int, dest int, visited []bool, path []int, paths [][]int) {
//add current node to path
path = append(path, src)
//mark current node as visited
visited[src] = true
//if the current node is the destination
//print the path and return
if src == dest {
//make a copy of path slice
buffer := make([]int, len(path))
copy(buffer, path)
//append the copy of path slice into the slice of paths
paths = append(paths, buffer)
fmt.Println(path) //Just for debugging purpose
return
}
for i := 1; i <= 7; i++ { //loop through all nodes
//if ith node is a neighbour of the current node and it is not visited
if myGraph[src][i] && visited[i] == false {
// call dfs on the current node
dfs(myGraph, i, dest, visited, path, paths)
//mark the current node as unvisited
//so that we can other paths to the final destination
visited[i] = false
//re-slice the slice - get rid of the current node
path = path[:len(path)-1]
}
}
}
预期输出:(在使用全局变量而不是将变量传递给函数时实现)
[[1 2 3 4 6 7] [1 2 3 6 7] [1 2 5 6 7] [1 3 2 5 6 7] [1 3 4 6 7] [1 3 6 7] [1 6 7]]
知道我做错了什么吗?
小唯快跑啊
尚方宝剑之说
相关分类