Problem 87b Solution

{-| Given a graph and a starting node, return all nodes in breadth-first order.
-}
breadthFirst : comparable -> Graph comparable -> List comparable
breadthFirst start (nodes, edges) =
    List.reverse (breadthFirst_ [start] [] (nodes, edges))


{-| Helper function for breadthFirst that recordes visited nodes to avoid
    cyclic paths.
-}
breadthFirst_ : List comparable -> List comparable -> Graph comparable -> List comparable
breadthFirst_ unvisited visited ( nodes, edges ) =
    case unvisited of
        [] ->
            visited

        u::us ->
            let
                nextNodes = unique
                    <| List.map (Tuple.second) 
                    <| (++) (List.filter (\( a, b ) -> a == u) edges)
                    <| List.map (\x -> ( Tuple.second x, Tuple.first x ))
                    <| List.filter (\( a, b ) -> b == u) edges

                newNodes = List.sort
                    <| List.filter (\x -> not (List.member x (u::visited))) nextNodes
            in
                breadthFirst_ (remove u (newNodes ++ unvisited)) (u::visited) (nodes, edges)



remove : a -> List a -> List a
remove x = 
  List.filter ((/=) x)


{-| Given a list, return all unique values in the list.
-}
unique : List comparable -> List comparable
unique list =
    Set.toList <| Set.fromList list

Back to problem

results matching ""

    No results matching ""