I have tried to find and print 3 shortest paths between two vertices in the undirected graph using BFS as DFS will not be optimal in this case, as it can go deep into the stack.
Wrote this function but not getting the correct response and also tried to find help over StackOverflow and other platforms but did not find a solution for undirected graph. This below function finds all the paths, but I can filter to 3 or any number.
I have taken reference from I found one solution - https://www.geeksforgeeks.org/print-paths-given-source-destination-using-bfs but it is not working for me. but it turns out to be not working for me.
func BFS(s, d *Vertex) [][]*Vertex {
routes := make([][]*Vertex, 0)
queue := NewFIFO()
path := make([]*Vertex, 0)
path = append(path, s)
queue.Push(path)
for queue.Len() != 0 {
p := queue.Pop()
path = p.([]*Vertex)
last := path[len(path)-1]
if last == d {
routes = append(routes, path)
}
for _, as := range last.AdjStations {
if !isVisited(as, path) {
newPath := make([]*Vertex, 0)
newPath = append(newPath, as)
queue.Push(newPath)
}
}
}
return routes
}
func isVisited(vertex *Vertex, path []*Vertex) bool {
for _, v := range path {
if v == vertex {
return true
}
}
return false
}