简体   繁体   中英

Algorithm for finding weight of path with lowest weight in weighted directed graph

I am given a G=(V,E) directed graph, and all of its edges have weight of either "0" or "1".

I'm given a vertex named "A" in the graph, and for each v in V, i need to find the weight of the path from A to v which has the lowest weight in time O(V+E). I have to use only BFS or DFS (although this is probably a BFS problem).

I though about making a new graph where vertices that have an edge of 0 between them are united and then run BFS on it, but that would ruin the graph direction (this would work if the graph was undirected or the weights were {2,1} and for an edge of 2 i would create a new vertex).

I would appreciate any help.

Thanks

I think it can be done with a combination of DFS and BFS.

In the original BFS for an unweighted graph, we have the invariant that the distance of nodes unexplored have a greater or equal distance to those nodes explored.

In our BFS, for each node we first do DFS through all 0 weighted edges, mark down the distance, and mark it as explored. Then we can continue the other nodes in our BFS.

Array Seen[] = false
Empty queue Q
E' = {(a, b) | (a, b) = 0 and (a, b) is of E}

DFS(V, E', u)
    for each v is adjacent to u in E' // (u, v) has an edge weighted 0
        if Seen[v] = false
            v.dist = u.dist
            DFS(V, E', v)
    Seen[u] = true
    Enqueue(Q, u)

BFS(V, E, source)
    Enqueue(Q, source)
    source.dist = 0
    DFS(V, E', source)
    while (Q is not empty)
        u = Dequeue(Q)
        for each v is adjacent to u in E
            if Seen[v] = false
                v.dist = u.dist + 1
                Enqueue(Q, v)
        Seen[u] = true

After running the BFS, it can give you all shortest distance from the node source. If you only want a shortest distance to a single node, simply terminate when you see the destination node. And yes, it meets the requirement of O(V+E) time complexity.

This problem can be modified to the problem of Single Source Shortest Path .

You just need to reverse all the edge directions and find the minimum distance of each vertex v from the vertex A.

It could be easily observed that if in the initial graph if we had a minimal path from some vertex v to A, after changing the edge directions we would have the same minimal path from A to v.

This could be simply done either by Dijkstra OR as the edges just have two values {0 and 1}, it could also be done by modified BFS (first go to vertexes with distance 0, then 1, then 2 and so on.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM