How does a Breadth-First Search work when looking for Shortest Path?

前端 未结 8 1466
太阳男子
太阳男子 2020-11-30 16:52

I\'ve done some research, and I seem to be missing one small part of this algorithm. I understand how a Breadth-First Search works, but I don\'t understand how exactly it wi

8条回答
  •  萌比男神i
    2020-11-30 17:09

    Visiting this thread after some period of inactivity, but given that I don't see a thorough answer, here's my two cents.

    Breadth-first search will always find the shortest path in an unweighted graph. The graph may be cyclic or acyclic.

    See below for pseudocode. This pseudocode assumes that you are using a queue to implement BFS. It also assumes you can mark vertices as visited, and that each vertex stores a distance parameter, which is initialized as infinity.

    mark all vertices as unvisited
    set the distance value of all vertices to infinity
    set the distance value of the start vertex to 0
    if the start vertex is the end vertex, return 0
    push the start vertex on the queue
    while(queue is not empty)   
        dequeue one vertex (we’ll call it x) off of the queue
        if x is not marked as visited:
            mark it as visited
            for all of the unmarked children of x:
                set their distance values to be the distance of x + 1
                if the value of x is the value of the end vertex: 
                    return the distance of x
                otherwise enqueue it to the queue
    if here: there is no path connecting the vertices
    

    Note that this approach doesn't work for weighted graphs - for that, see Dijkstra's algorithm.

提交回复
热议问题