0

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
}
kamal
  • 996
  • 15
  • 25
  • I think one way to do it would be count number of vertices in the shortest path. Normal dfs to find all path between source and vertex will be an overkill. So you can use dfs with pruning such that if number of vertices exceed the minimum number of vertices don't recurse any further also you can keep count of number of solutions in dfs and if number of solutions exceed 3 stop the recursion. – Wasim Ahmad Apr 13 '20 at 20:39
  • A simpler way would be to use a parent array and set the parent[v] = u in bfs, now backtrack from the parent[destination] till you reach source to find a single solution. To find all the solutions you need to find paths in parent array which lead to destination in same number of jumps as the shortest. This can be done with stack I think. – Wasim Ahmad Apr 13 '20 at 20:46
  • So, your function does everything you need except that it doesn't stop at 3 paths? – beaker Apr 13 '20 at 21:38

0 Answers0