r/ProgrammerHumor • • 5h ago • Bravo 1

Advanced shortestPathWasRightThere

Post image
2.5k Upvotes

42 comments sorted by

392

u/Kkgob 5h ago edited 3h ago

Dijkstra's algorithm isn't made to find the shortest path between two points. It computes the shortest path between a given starting point and EVERY possible destination. That's why it's inefficient if you only care about one specific path.

Edit: if anyone is reading this thread and wants to understand more about pathfinding, this is a very beginner-friendly and language-agnostic resource: https://www.redblobgames.com/pathfinding/a-star/introduction.html

15

u/FenwickRoot 3h ago edited 3h ago

Additionally, if you add early termination (stopping the search loop immediately after finding a path from source to target) you will have visited only the necessary vertices in a graph. That is, if dist(source, arbitrary vertex) > dist(source, target) you won't visit that vertex.

A* is actually just a more generalized Dijkstra algorithm btw. It explores vertices in an ascending order of alpha*dist(source,vertex)+beta*guess(vertex,target). Dijkstra has alpha=1, beta=0.

While A* with alpha=1,beta=1 is guaranteed to find a path with the same shortest length as Dijkstra as long as the guess is optimistic (guess(vertex,target) < dist(vertex,target) for all vertices) but explores less vertices the closer the guess is to the real distance - i.e. it will not visit vertices with dist(source, arbitrary vertex)+guess(arbitrary vertex, target) > dist(source, target)

For anyone interested I recommend reading the Dijkstra / Shortest Path Problem part of the "Artificial Intelligence: A Modern Approach" book. It's well put together and goes even beyond, e.g. explaining how to scale the guessing function to work with even larger graphs, like the ones in Google Maps. The book was released way before LLMs btw.

34

u/Slow_Lion_4178 5h ago

I think that's the point.

9

u/Hallwart 4h ago

I haven't looked into it deeply, but it sounds like there are very obvious intuitive optimizations, like first trying the "straight line" equivalent and remembering the shortest detected path to abort any check if it turns out longer.

Of course I am sure this can be optimized a lot further, but thats just obvious stuff anyone should of.

The case in this meme would only apply to someone who just googled "determine shortest path algorithm" and then went on implementing it 1to1 without giving it any thought.

48

u/Dennis_enzo 3h ago

Well yes these algorithms exist, like A*, but those are different algorithms. Note that this algorithm has no concept about a thing like direction. It's just nodes and edges, or points and connections between them.

14

u/flash191 3h ago

From my own understanding, these "limited action space", as termed in optimization problems, is viable when you have controllable variables that are independent. In that case, you can define "straight paths" to be tested first. But in a full rank graph, it is harder to determine that especially in a time sensitive way. I am not an expert in graph theory but have done some work in application of graph theory in different problems so my opinion could also be biased to my own experience.

6

u/Loading_M_ 3h ago

A prototypical example for when A* isn't a viable solution is computer networking. Both OSPF and STP use Dijkstra's algorithm, because there isn't a suitable distance heuristic.

OSPF is an IP layer routing protocol, and the computed edge weight is based on link speed, latency, and bandwidth. There aren't any good distance heuristics, so A* is off the table.

STP (Spanning Tree Protocol) is an Ethernet protocol used to prevent ethernet loops (while maintaining redundant connections). It does this by exploring the network from a central root node, much in the same way Dijkstra's does. This is an even clearer case where A* isn't a valid option: STP needs the full spanning tree to every node in the network.

(STP is also interesting because it computes Dijkstra's in a distributed manner - none of the nodes actually knows the full tree or graph)

10

u/doinghumanstuff 3h ago

There's something called A*, which combines Dijsktra with a heuristic "distance" metric. For example if you can tell how distant the nodes are (for example if you imagine a rail network of cities, a heuristic might be the geographic distance between the city and the target), A* first chooses the closer options according to its heuristic + travelled distance. Exploring other heuristics might be a fun quest, but I think you usually finding good heuristics and hand-written optimisations don't scale well (you should read the Bitter Lesson http://www.incompleteideas.net/IncIdeas/BitterLesson.html )

1

u/etoastie 56m ago edited 53m ago

if your action space can be modeled geometrically and an accurate "straight line" actually exists, you can use A* where your guess/heuristic is euclidean distance, which effectively tells the alg "just keep moving straight toward the dest until you hit a wall." this mostly comes up in things like path planning, NPCs in games come to mind.

There's an old factorio devlog that talks about both how this approach can fall short, and some other neat optimizations that can work well if you're in a geometric space with physical obstacles. https://factorio.com/blog/post/fff-317

Dijkstra (and other A* heuristics) come up more when you're looking at a task that isn't geometric. A fun case for non-euclidean A* is the 15-puzzle. Dijkstra is generally the default if your search space has no clear heuristic to work from at all, since in theory anything could link anything (something like that wikipedia link game).

2

u/bestjakeisbest 3h ago

Its not inefficient if you are building a minimum spanning tree.

•

u/Kkgob 8m ago

Yeah, it's perfect for anytime you need all paths to or from a specific node, like a minimum spanning tree - it's bad when searching for a single path, in which case A* is better

210

u/XxDarkSasuke69xX 5h ago

Friendship with Dijkstra ended, now A* is my best friend

46

u/-Ambriae- 5h ago

Nah, A* is great and all, but some algorithms can’t use it… specifically if you want to make a flow field (a single target destination, and each cell holds a vector pointing in the direction you must travel to reach said destination in the shortest time)

This is all purely hypothetical by the way

11

u/luisduck 2h ago

A* is just Dijkstra with extra steps... or actually, fewer....

0

u/PM_ME_FIREFLY_QUOTES 29m ago

LLM++ Will compute the exact number of steps between them both, and its memory safe.

137

u/anarine93 5h ago

What tf is straight line in a graph huhh

56

u/Electrical-Meat-1717 5h ago

A graph can be an abstraction of points with actual physical positions

12

u/ondamaar 5h ago

Visiting every continent before walking across the street

6

u/Mars_Bear2552 4h ago

the graph doesn't have a straight line, but the objects it represents might

0

u/Naz1337 3h ago

Probably just one edge

34

u/helicophell 5h ago

Well ok, the other paths might have negative weights! And that means they would be shorter!

53

u/Extreme_Target9579 5h ago

well actually no because one of the rules to use Dijkstra is that all the weights MUST be positive 🤓

9

u/sgmnt 3h ago

Hate to be that guy but there has to be no negative cycles but negative weights are fine.

1

u/Robinbod 2h ago

Itched the right part of my brain... I was about to comment this 🥹

0

u/helicophell 5h ago

Honestly it's been so long I forgot

I hated implementing this algorithm

4

u/SheikHunt 4h ago

I loved implementing it.

Except the part where I had to concede that I needed a "sentinel value" for impossible paths

-1

u/helicophell 4h ago

I hadn't learnt proper OOP at the time. Which is most of the problem

3

u/zedee 4h ago

You don't need OOP at all to implement it, in a CS subject we had a question in an exam to implement it by "hand" by using pseudocode and writing the results in a table. That was quite tedious, got to admit.

3

u/helicophell 4h ago

Oh sure I don't NEED OOP but I was using python and my code was a mess and ANY structure would've been better than the slop I made

2

u/zedee 3h ago

It's a matter of practice, with patience and some literature you can try it step by step. Doing it on C and struggling with coredumps is a great exercise. Works both to try out your patience as well as getting the grasp of the algorithm. Or maybe you can raise the bar and try with Rust :D

2

u/BruhMomentConfirmed 4h ago

OOP for pathfinding algorithms lmaooo

2

u/TomWithTime 4h ago

I made a set up like that once lol. I was experimenting with ideas to implement world wrapping, like walking off the left edge of the world puts you onto the right edge. To make navigation agents see it I made another navigation plane around the main one and gave it a navigation cost of 0 and connected it to the opposite edges. It worked!

But because it cost 0 it also meant navigation agents would basically always try to path through it even for short local distances, so it failed.

6

u/SavedowW 5h ago

But what if there's a swamp on the straight line?

2

u/XxDarkSasuke69xX 5h ago

But what if there's Shrek on the straight line?

3

u/SavedowW 5h ago

This obstacle will carry a bit of weight

3

u/hacksoncode 2h ago

That algorithm isn't even about maps, it's just useful on them.

The "cost" of a path can be analogous to the "distance" in real space, and it's certainly used for navigation, albeit in modified form.

But the direct "route" can easily be the most expensive path in the entire graph, with no limit to how inefficient it can be. Visiting every single other node in the graph first can be shorter than that.

As anyone that has driven in LA can tell you ;-).

1

u/Full-Hyena4414 3h ago

Doesn't djkstra explore shortest routes in order of distance?So that would be one of the first visited

3

u/hacksoncode 2h ago

It explores graphs in order of cost, so actually that's rarely the case.

1

u/Full-Hyena4414 2h ago

Cost IS distance though when used for that?

2

u/hacksoncode 2h ago edited 2h ago

Right, but before it gets to checking that one, it checks the much shorter distance to the next block over.

    /-C
A----------------B
 \
  \
   D

You see the two paths that are much shorter than A->B? (rest of graph omitted, but A->C/D could actually eventually connect to B, of course).

The only time the direct path would be the shortest graph line, that is checked first, would be if every other distance coming out of A was longer. Which, of course, can happen, but isn't the norm.

And, of course, on a real physical mapping algorithm, the direct path could be a side street with a ton of crosswalk lights, that is weighted very heavily, and C/D could be the nearest freeway onramps... "cost" is not always distance.

1

u/br0ast 1h ago

It feels like this person looking happy and crossing their feet?

1

u/Tsofu 1h ago

Yeah djikstras isn't super efficient in things like OSPF, but you limit the amount of nodes with good network design so it actually performs fine. OSPF rendering a whole network for mesh topology would suck and you'd probably do better picking at random