Shortest Path For A Dag

后端 未结 1 1507
礼貌的吻别
礼貌的吻别 2021-02-10 01:13

I have a graph with an s and t vertex that I need to find the shortest path between. The graph has a lot of special properties that I would like to capitalize on:

1条回答
  •  梦谈多话
    2021-02-10 02:05

    I'm going to go against my intuition and assume this isn't homework. You have to take advantage of the information that a topological ordering gives you. Whenever you examine the node n in a topological ordering, you have the guarantee that you've already traversed every possible path to n. Using this it's clear to see that you can generate the shortest path with one linear scan of a topological ordering (pseudocode):

    Graph g
    Source s
    top_sorted_list = top_sort(g)
    
    cost = {} // A mapping between a node, the cost of its shortest path, and 
              //its parent in the shortest path
    
    for each vertex v in top_sorted_list:
      cost[vertex].cost = inf
      cost[vertex].parent = None
    
    cost[s] = 0
    
    for each vertex v in top_sorted_list:
       for each edge e in adjacensies of v:
          if cost[e.dest].cost > cost[v].cost + e.weight:
            cost[e.dest].cost =  cost[v].cost + e.weight
            e.dest.parent = v
    

    Now you can look up any shortest path from s to a destination. You'd just need to look up the destination in the cost mapping, get it's parent, and repeat this process until you get a node whose parent is s, then you have the shortest path.

    0 讨论(0)
提交回复
热议问题