一个简单的路径查找问题

    技术2022-05-20  31

    这是网上的haskell99题中第81题

    Problem 81

    (**) Path from one node to another one

    Write a function that, given two nodes a and b in a graph, returns all the acyclic paths from a to b.

    Example in Haskell:

    paths 1 4 [(1,2),(2,3),(1,3),(3,4),(4,2),(5,6)] [[1,2,3,4],[1,3,4]] paths 2 6 [(1,2),(2,3),(1,3),(3,4),(4,2),(5,6)] [] 以前都是用C++来解决图论问题,现在用一个简单的Haskell程序更见清晰明了 paths :: Int -> Int -> [(Int , Int)] -> [[Int]] paths start end zs = let (xs,ys) = partition (/(_,z) -> z == end ) zs in map (++ [ end] ) ( concat . map (/(e, _) -> if e == start then [[start]] else paths start e ys) $ xs )


    最新回复(0)