elm-community / graph

Functional Graph Library in Elm.

Home Page:http://package.elm-lang.org/packages/elm-community/graph/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

"Shortest Path" for an unweighted graph

erlandsona opened this issue · comments

I'm having a really difficult time figuring out how to return a "shortest path" between two nodes in my graph using Graph.bfs or Graph.guidedBfs... Joël Quenneville was kind enough to help me out with an implementation but I still feel pretty lost in how / why it works.

I was curious about where bfs / guidedBfs fit or how they help to create this "shortest path"?

Here's the Integer example I've worked up from refactoring of what Joel worked up with me.
https://ellie-app.com/3Xm9Xh3tSwFa1
Here's the same example designed to return the path as a list of the labels of each node in the path.
https://ellie-app.com/3XmbBGd3QbVa1

You can see where I'm currently passing bogus values because the entire graph is being traversed...

Is there a way to use the bfs function to only traverse as many nodes as necessary to find the shortest path?

I'm afraid there isn't. The graph traversals currently always perform a complete traversal.

One could remedy part of the bogus value situation by using a type like https://package.elm-lang.org/packages/mgold/elm-nonempty-list/latest/List-Nonempty for the path passed into NodeVisitors. I'd consider that for a future version.

The other bogus value could go away if you replaced the accumulator with Maybe Int. In fact, there is no value to return when end isn't part of the graph and your current implementation would return 7777 in that case, which I'd consider a bug.

I'm not exactly sure what you had in mind but here's what I came up with?

https://ellie-app.com/3Xm9Xh3tSwFa1

Thanks!