How to find shortest path in this type of maze

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 :)


What you have is a "simple" graph problem. The graph connectivity is the legal moves you have. The start node is your red dot. To get a single terminal node, invent one more circle outside the given maze; connect all the real exit nodes to the new circle with a move of zero cost.

Now, apply Dijkstra's algorithm. Done.


Another way to look at the problem is with recursion. Move the red dot, marking the old location black. Recur from the new position. Return when you exit (return path length 1) or have no legal moves (return path length infinite). Keep the shortest known path.

Do those get you un-stuck?