Turn Right Right Problem

I want anyone to post a code of following problem:

Given a table whose size is taken from the user say M*N size 2D Array.

Initial position is top left block and direction is Right side.
On each move,you need to turn 1 right and move 1 step forward, and if you encounter already visited block OR wall (wall means end of the array), turn 1 more time right and so on.

Preferred language is JAVA.
Output is no of steps moved.

For test cases :
i/p is 3 X 3 o/p = 9

i/p is 2 X 3 o/p is 4

i/p is 7 X 4 o/p is 18