在给定图表中找到“足够短”的路径

时间:2015-04-27 02:46:46

标签: graph shortest-path

我需要设计一种算法来寻找公共交通系统中的路径。从理论上讲,只需要最好的(最低成本)路径,但实际上它是不同的。在公共交通系统中旅行时,很难定义成本,它不能简化为旅行时间,等待时间,转移时间,公共汽车/地铁费等,都需要考虑。

首先,我需要简化问题,设计一个成本函数,它是所有那些“时间”和“费用”的组合,然后使用图算法找到几条路径(3~5路径)。最后向最终用户展示所有这些路径并让他们做出决定。

我需要提出多条路径的原因是,对于不同的用户/情况,这些“时间”和“费用”是不同的,因此提供一些路径比给出“最佳”路径更好。 / p>

像A *这样的算法很适合找到最短路径,但我怎样才能在图中找到那些“足够短”的路径?或者我怎样才能找到最短的N路径?

顺便说一下,我甚至不需要找到最短路径,因为在实践中最终用户永远不会知道最短路径(除非最短路径是明显的),如果结果接近最短路径,他们会很高兴

2 个答案:

答案 0 :(得分:0)

A * star的“成本”比你想象的更通用。 A *通常用节点来解释,节点的成本只是距离。但是,我们可以加强一点。

我没有看到你喜欢的语言,也许是Graph?哦,这是一些c ++:

namespace Astar
{
  struct CostEvaluation
  {
    int distance_cost;
    int transfer_cost;
    // others

    int costToTraverseNodes( const Node& first, const Node& second ) const
    {
      int distance = // apply distance_cost to distance between nodes
      int transfer = // apply transfer_cost if there is a transfer between nodes

      return distance + transfer;
    }
  }
}

现在,A *的实际实施将采用CostEvaluation对象来确定路线上的成本。如果转移无关紧要,请将transfer_cost设置为零。

就“足够好”的路线而言:我相信其他人能够更好地帮助你,但我觉得你可能会遇到这样一种情况,即程序会说“哦,你想成为在一个小时内,但最好的路线只需要20分钟?在这里,绕圈四十分钟,这已经足够好了。“

答案 1 :(得分:0)

正如我在评论中暗示的那样,可以创建一个报告多条路线的修改后的A *版本。我只是把我的实现推到了显然确认这个陈述的程度。

下面的代码以“经典”A *实现开头,我保留了这个实现,因此可以研究“经典”和“修改”之间的差异。

修改版本的基本思想是并行开始向前和向后搜索。考虑到A *的“贪婪”主要由其启发式函数(h(x))驱动,这通常也会产生更强大的结果。有可能构建案例,其中贪婪选择在路线开始时快速进展,而朝向末端的路线“大幅减速”。从两侧(源,目标)开始,这种效果可以减轻到比特。 (如果计算到最后,它应该始终是最佳路线,如果不一定是相同的路线。如果要计算两个方向上的“经典”结束条件,可能会产生下面的图片,显示两者方向产生2条不同的路径。

2 routes yielded from calculating path in both directions

现在,两个方向的“探索列表”可用于查找何时搜索,例如“前进”,下一个节点已经通过“向后”搜索进行了探索 - 反之亦然。显然,两次搜索之间的那些“连接点”产生了一条路线,这条路线不一定是最优的,而是一条有效的路线。

我的实现跟踪那些中间路线,我没有费心去收集它们。跟踪显示两个探索列表“相遇”的节点的id以及路由的结果2部分(源 - >会合点,会合点 - >目的地)。

现在,使用这些中间列表以及一些后期处理,例如通过根据启发函数的单个维度(例如舒适度,速度等)评估路线,应该可以找到足够好的路线选择,与这些维度中的不同权衡相关联。

完整的F#脚本大约有340行 - 这个网站有点太长了,所以我省略了一些不必要的部分(例如我的渲染功能,创建这些位图等等。

module AStar =
    module Internals =
        let makeRoute (explo : Map<int,(int * float)>) at tgt =
            let rec loop at acc =
                let dst,c = explo.[at] 
                match at,dst with
                | (_,b) when b = tgt -> (at,c) :: acc
                | (_,b) -> loop b ((at,c) :: acc)
            [(tgt,0.0)] @ loop at [] 

        let makeRouteBackward (exploBW : Map<int, (int * float)>) at tgt =
            let rec loop at acc = 
                let src,c = exploBW.[at]
                match at,src with
                | (_,b) when b = tgt -> acc @ [(at,c)]
                | (_,b) -> loop b (acc @ [at,c])
            let r = loop at [] @ [(tgt,0.0)]
            let rev = List.rev r
            List.zip r rev |> List.map (fun ((id1,c1),(id2,c2)) -> id1,c2) 

    let classic neighbors h cost start goal =
        let prioSelect (lopen : (int * float) list) =
            let sorted = List.sortBy (fun (id,p) -> p) lopen //|> List.rev
            (fst (List.head sorted), List.tail sorted)
        let rec search (lopen : (int * float) list) (routes : Map<int,int * float>) =
            let rec searchNeighbors cur nl o (r : Map<int,(int * float)>) =
                match nl with
                | [] -> o,r
                | next::others -> 
                    let newCost = (snd (r.[cur])) + cost cur next
                    if (not (Map.containsKey next r)) || (newCost < snd r.[next])
                    then
                        let r1 = r |> Map.remove next |> Map.add next (cur,newCost)
                        let prio = newCost + h next goal
                        //printfn "current = %d -- next = %d -- newCost = %f -- prio = %f -- h = %f" cur next newCost prio (h next goal)
                        let o1 = (next,prio) :: o
                        searchNeighbors cur others o1 r1
                    else
                        searchNeighbors cur others o r
            match lopen with 
            | [] -> []
            | _::_ ->
                let current,rest = prioSelect lopen
                if current = goal then Internals.makeRoute routes current start
                else
                    let lopen1,routes1 = searchNeighbors current (neighbors current) rest routes
                    search lopen1 routes1
        search [start,0.] (Map.ofList [start,(start,0.0)])

    let twoWay sources targets hforward hbackward costforward costbackward (start : int) (goal : int) (n : int) rr =
        let prioSelect (lopen : (int * float) list) =
            let sorted = List.sortBy (fun (id,p) -> p) lopen //|> List.rev
            (fst (List.head sorted), List.tail sorted)
        let searchforward lopen exploredF exploredB nfound acc =
            let rec searchNeighbors cur nl o (r : Map<int,(int * float)>) =
                match nl with
                | [] -> o,r
                | next::others -> 
                    //printfn "fwd: current = %d -- next = %d -- nl = %A  -- r = %A" cur next nl r
                    let newCost = (snd (r.[cur])) + costforward cur next
                    if (not (Map.containsKey next r)) || (newCost < snd r.[next])
                    then
                        let r1 = r |> Map.remove next |> Map.add next (cur,newCost)
                        let prio = newCost + hforward next goal
                        let o1 = (next,prio) :: o
                        if Map.containsKey next exploredB then
                            rr (next, Internals.makeRoute r1 next start, Internals.makeRouteBackward exploredB next goal)
                        searchNeighbors cur others o1 r1
                    else
                        searchNeighbors cur others o r
            match lopen with 
            | [] -> (lopen,exploredF,0,acc)
            | _::_ ->
                let current,rest = prioSelect lopen
                if current = goal then
                   (rest,exploredF,nfound+1,acc @ [Internals.makeRoute exploredF current start] )
                else
                    let lopen1,explored1 = searchNeighbors current (targets current) rest exploredF
                    (lopen1, explored1, nfound, acc)
        let searchbackward lopen exploredB exploredF nfound acc = 
            let rec searchNeighbors cur nl o (r : Map<int,(int * float)>) =
                match nl with
                | [] -> o,r
                | next::others -> 
                    //printfn "bwd: current = %d -- next = %d -- nl = %A  -- r = %A" cur next nl r
                    let newCost = (snd (r.[cur])) + costbackward cur next
                    if (not (Map.containsKey next r)) || (newCost < snd r.[next])
                    then
                        let r1 = r |> Map.remove next |> Map.add next (cur,newCost)
                        let prio = newCost + hbackward next start
                        let o1 = (next,prio) :: o
                        searchNeighbors cur others o1 r1
                    else
                        searchNeighbors cur others o r
            match lopen with 
            | [] -> (lopen,exploredB,0,acc)
            | _::_ ->
                let current,rest = prioSelect lopen
                if current = start then
                   //(rest,explored,nfound+1,acc @ [Internals.makeRoute explored current goal []])
                   (rest,exploredB,nfound+1,acc @ [Internals.makeRouteBackward exploredB current goal] )
                else
                    let lopen1,explored1 = searchNeighbors current (sources current) rest exploredB
                    (lopen1, explored1, nfound, acc)
        let rec driver openF openB exploredF exploredB nfoundF nfoundB accF accB =
            let openF1, exploredF1,nfoundF1,accF1 = searchforward openF exploredF exploredB nfoundF accF
            let openB1, exploredB1,nfoundB1,accB1 = searchbackward openB exploredB exploredF nfoundB accB

            match (nfoundF1+nfoundB1), List.isEmpty openF1, List.isEmpty openB1 with
            | (s,false,false) when s < n -> 
                driver openF1 openB1 exploredF1 exploredB1 nfoundF1 nfoundB1 accF1 accB1
            | _ -> 
                accF1 @ accB1
        driver [start,0.0] [goal,0.0] (Map.ofList [start,(start,0.0)]) (Map.ofList [goal,(goal,0.0)]) 0 0 [] []


// Location : x,y coordinate or lat/long - whatever.
// Edges: (id,cost) list
type Node = { Id : int; Location : int * int; Edges : (int * float) list; EdgesBackward : (int * float) list}

type Graph = Map<int,Node>

let addNode node graph =
    Map.add (node.Id) node graph

let newNode idgen x y  = 
    { Id = idgen(); Location = (x,y); Edges = []; EdgesBackward = [] }

let addEdge id cost node =
    { node with Node.Edges = node.Edges @ [(id,cost)]; }

let addEdgeBackward id cost node =
    { node with Node.EdgesBackward = node.EdgesBackward @ [(id,cost)]; }

let idgen startvalue =
    let next = ref startvalue
    fun () -> 
        let id = !next
        next := !next + 1
        id

let appendNode node nodeList = nodeList @ [node]

let sq x = x*x
let distance p1 p2 =
    let x1,y1 = p1
    let x2,y2 = p2
    sqrt( float (sq (x2-x1) + sq (y2-y1)) )

let solve (g : Graph) s e =
    let ns id =
        g.[id].Edges |> List.map (fun (id,c) -> id)
    let h at goal =
        float (distance (g.[at].Location) (g.[goal].Location))
    let c a b =
        g.[a].Edges |> List.pick (fun (id,cost) -> if id = b then Some(cost) else None)
    [AStar.classic ns h c s e]  // give it the same return type as solveTwoWay to make stuff below easier and shorter

let solveTwoWay (g : Graph) s e n =
    let edges id =
        let nl = g.[id].Edges |> List.map (fun (id,c) -> id)
        //printfn "2way edges id = %d list = %A" id nl
        nl
    let edgesBackward id =
        let nl = g.[id].EdgesBackward |> List.map (fun (id,c) -> id)
        //printfn "2way backwards edges id = %d list = %A" id nl
        nl
    let hforward at goal =
        float (distance (g.[at].Location) (g.[goal].Location))
    let hbackward at start =
        float (distance (g.[at].Location) (g.[start].Location))
    let costF a b =
        g.[a].Edges |> List.pick (fun (id,cost) -> if id = b then Some(cost) else None)
    let costB a b =
        g.[a].EdgesBackward |> List.pick (fun (id,cost) -> if id = b then Some(cost) else None)
    let  debugView arg =
        let id,r1,r2 = arg
        printfn "meeting at %d: r1 = %A r2 = %A" id r1 r2

    AStar.twoWay edgesBackward edges hforward hbackward costF costB s e n debugView
let solveProblem problem =
    let g, start, goal = problem
    g,start,goal,solve g start goal

let solveProblemTwoWay problem n =
    let g, start, goal = problem
    g,start,goal,solveTwoWay g start goal n

let save name solution =
    let graph, start, goal, routes = solution
    use  writer = System.IO.File.CreateText("""E:\temp\""" + name + """.txt""")
    fprintf writer "------------------------------------\n start = %d ----> goal = %d: %d routes found.\n" start goal (List.length routes)
    fprintf writer "Graph:\n"
    graph |> Map.iter
        (fun id node ->
            fprintf writer "Node: %A\n" node
        )
    routes |> List.iteri 
        (fun index route ->
            fprintf writer "Route %d: %A\n" index route
        )
// An example problem I used to play with:
// The graph is such, that  the nodes are connected to the right and     
// downwards and diagonally downwards only. 
// The cost is either 1.0 or sqrt(2), for the horizontal or vertical and
// the diagonal connection, respectively.
let problem2 () =
    let newNodeAN = newNode (idgen 0)
    let cond c x n =
        if c then n |> x else n
    let accessCost p =
        match p with
        | (4,4) | (4,5) | (5,4) | (5,5) -> 10.0
        | _ -> 1.0
    let right (n : Node) : Node =
        let t = 1 + fst n.Location, snd n.Location
        let c = accessCost t
        n 
        |> cond (fst n.Location < 9) (fun n -> addEdge (n.Id + 1) c n)
        |> cond (fst n.Location > 0) (fun n -> addEdgeBackward (n.Id - 1) c n)
    let down n =
        let t = fst n.Location, 1 + snd n.Location
        let c = accessCost t
        n
        |> cond (snd n.Location < 9) (fun n -> addEdge (n.Id + 10) c n)
        |> cond (snd n.Location > 0) (fun n -> addEdgeBackward (n.Id - 10) c n)
    let diagdown n =
        let t = 1 + fst n.Location, 1 + snd n.Location
        let c = (sqrt(2.0)) * accessCost t
        n
        |> cond (fst n.Location < 9 && snd n.Location < 9) (fun n -> addEdge (n.Id + 11) c n)
        |> cond (fst n.Location > 0 && snd n.Location > 0) (fun n -> addEdgeBackward (n.Id - 11) c n)

    [
        for y = 0 to 9 do
            for x = 0 to 9 do
                yield newNodeAN x y
    ]
    |> List.map 
        (fun n ->
            n 
            |> right
            |> down
            |> diagdown 
        )
    |> List.map (fun n -> (n.Id,n))
    |> Map.ofList
    , 0, 99

// Last not least, the code can be executed like this:
// And since both implementations yield the same data structures,
// they can be used interchangeably and compared to each other.
solveProblemTwoWay (problem2() 5) |> save "problem2_solution"

在运行时打印的输出显示“中间路径”,然后如下所示:

  

...
  48日开会:
  r1 = [(0,0.0); (11,1.414213562); (12,2.414213562); (23,3.828427125);    (34,5.242640687); (35,6.242640687); (46,7.656854249); (47,8.656854249);    (48,9.656854249)]
  r2 = [(48,0.0); (58,1.414213562); (68,2.414213562); (78,3.414213562);    (88,4.414213562); (99,5.414213562)]
  会议在84:
  r1 = [(0,0.0); (11,1.414213562); (21,2.414213562); (32,3.828427125);    (43,4.242640687); (53,6.242640687); (64,7.656854249); (74,8.656854249);    (84,9.656854249)]
  r2 = [(84,0.0); (85,1.414213562); (86,2.414213562); (87,3.414213562);    (88,4.414213562); (99,5.414213562)]
  会议在95:
  r1 = [(0,0.0); (11,1.414213562); (21,2.414213562); (32,3.828427125);    (43,4.242640687); (53,6.242640687); (64,7.656854249); (75,9.071067812);    (85,10.07106781); (95,11.07106781)]
  r2 = [(95,0.0); (96,1.0); (97,2.0); (98,3.0); (99,4.0)]
  ...