Skip to content
Advertisement

Maze pathfinding implementation (BFS) not giving correct path [closed]

I am trying to get the shortest path for a maze with a ball: the ball is rolling until it hits a wall. I use Dijkstra’s algorithm using heapq for priority queue. However, I get a non-optimal path as result.

Here is my code with sample input:

JavaScript

The idea is to compare the distance and if it is equal, pick the path with fewer changes of direction.

I am currently getting rdrludlrdrudludldldr (i.e. right-down-right-left-…) as an output, but the sequence “rl” found at index 2 doesn’t make sense: “Right” should not be followed by “Left” nor should “Up” be followed by “Down” and vice versa. Such a sequence is evidently not optimal as the first of those two moves could just be omitted to get the ball at the same location and travelling shorter distance.

The expected output for this maze is drururdrdrurdrd.

Why am I not getting the shortest path?

Advertisement

Answer

The problem is that the __lt__ function is not doing what it should.

It should return a boolean which is true when self is to be considered less than p. As you currently return an integer result, which often is non-zero you get into the situation where a pair (p, q) of points would have both p < q and q < p as true… which leads to erratic behaviour.

Here is how you could define it:

JavaScript

With this change the returned path is

JavaScript

Simplification

Instead of creating the class Point, you could use named tuples, which makes everything easier (and faster). You would just need to change the order of the “properties” so that these points compare in the desired way, i.e. directions should come before coordinates and the length of the directions string should get its own property:

JavaScript

And then make the appropriate change where you call Point:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement