One approach to this problem is as follows:
Suppose the input grid
0 0 0 0
0 0 1 1
0 0 0 0
0 0 0 0
start is (1,1) and end is (4,4).
Now, starting from 1.1, mark all elements 0 in horizontal and vertical positions to the starting point, as VISITED, and mark the change in direction as 0. When you visit them, put them in the queue. After the first iteration, the grid looks like
0 VVV
V 0 1 1
V 0 0 0
V 0 0 0
Then we get the next item from the queue and continue. Now we increase the change of direction by +1. When we reach the end point, we return a minimal change in direction.
source share