Create a graph by building four nodes for each position in the maze. Each node corresponds to a specific direction: N, S, E, W.
Between each node and no more than three neighboring neighbors there will be edges: one - "front", "back" and "right" (if they exist). The edge leading to the node in the front and back will have a weight of 0 (since the path length does not matter), while the edge to the node in the right will have a weight of 1 (this is what the cost of the correct turning).
Once the graph is set up (and probably the best way to do this is to reuse the original maze view), the modified widthth option — the first search algorithm will solve the problem.
The trick for handling 0/1 edge weights is to use deque instead of the standard queue implementation. In particular, nodes that have reached up to 0 weight edges will be pushed in front of the deck, and those reached through the edges of weight 1 will be shifted to the back.
source share