algorithmpathshortest-pathbreadth-first-searchshortest

How to find shortest path in this type of maze


Red

Red Dot - Represents the initial location
Black Dot - Already occupied
Green - Free to occupy
Destination - Boundry of the matrix [which means either x = 0 or y = 0 or x = 8 or y = 8]

eg. Example:

The red dot can place itself only one move at a time and can move in one of green six circles which are attached to it. What will be the fastest method to calculate the shortest path in this type of maze.


Solution

  • First of all, you don't need Dijkstra, because all values of the edges are the same. You can use a simple BFS or DFS algorithm. Worst case complexities are the same but I would use BFS as it has better average case complexity. However, O(|V|+|E|) is the fastest you can get here and it's proven.

    How to have your graph represented? The best way is to keep a list of neighbours for each Node. Black dots from your example aren't counted as a neighbours. So in your example, each node would have 0(fully covered by black dots) to 6 neighbours. Then, you can get anywhere you can get from any node point via these lists.

    BFS algorithm has a property that it assigns each node a layer, which means how far it is from a starting node. You start at your starting point and your current layer will be 0. Then you just follow all nodes from a current layer(usually kept at queue) and try to find it's neighbours(from their list of neighbours), which doesn't have layer assigned and you assign them +1 higher layer. Once you find your Node, (which can still have x,y as attributes for border checking (or property bool border)), at the border of your maze, you know it's as far as your layer value is. If you want to print the exact way, you only have to find way back (via your lists of neighbours) which meets the condition that every step is at -1 layer lower. This will print the way from end to start, but I'm sure you'll get your result with a little help from Stack data structure :)