You can simplify your code for the Dijkstra's algorithm.
Firstly rather than creating D[M][N] for storing distances to various nodes you can create a single D array to store all the distances and assign each node a value i.e, value 0 for the top left disc and so on.
Assuming some value say 0 is assigned to the top left disc it is quite trivial to find its neighbours and there by eliminating the need for a 2D matrix.
Next pre calculate all the edge weights (which in this case is the # of times you have to rotate a circle) and store it along with the neighbouring vertices of a node in adjacency list.
Next you can simply run Dijkstra's algorithm and compute the shortest distance to the bottom right disc.