×As P2 you want to force P1 to traverse an entire side of the grid, and then force P1 to return back the way they came in order to progress. Once they've retraced their steps and gone to the next available cell, you let them continue in one direction, but again not in the other. So using the 3x3 example, a sample game could look like this:
right allow
down block
right allow
down block
left
left
down allow
down allow
right block
up
right allow
down allow
right block
up
right allow
down allow - end
MATH FOLLOWS
For the NxM case, at a minimum they would have to traverse N, with an extra blocked move on each square except the first one, then return along N. That's 3(N-1) or 3N-3 moves to traverse the side, plus 1 more to get to the next available square. Then they'd have to traverse either N or M again in the same way, and so on and so forth.
So for our 3x3 grid, with P1 running a zigzag pattern, we have 6 moves to get back to O, 1 move to move down, 3 moves to get back to O-1, 1 move to get to 1-1, 3 moves to get back to it and 2 moves to finish the maze, which equals 6+1+3+1+3+2=16. Running each row all at once, gives 6 back to O, 1 to move down, 6 back to O-1, 1 to move down, 2 to finish, or 6+1+6+1+2=16 again.
For a more complex (and more relevantly, uneven-sided) 5x4 we have 12 back to O, 1 down, 6 back to O-1, 1 over, 9 back to 1-1, 1 down, 3 back to 1-2, 1 over, 6 back to 2-2, 1 down, 2 to win, which equals 12+1+6+1+9+1+3+1+6+1+2 or 43 in a zigzag. Or, going row by row, 12+1+12+1+12+1+4=43.
So this method always takes the same number of moves no matter which way P1 tries to take it. Knowing that, we can simplify things down a little. We know it takes 3(N-1) moves to traverse each row, plus 1 to move on to the next row, or 3(N-1)+1. We have to do that M-1 times (if there's 3 rows as value M, we need to do 2 full rows this way). That gives us (3(N-1)+1)(M-1) to arrive on the last row. Then we move N-1 more times to get to the end square. So our formula is (3(N-1)+1)(M-1)+N-1. Expanding gives:
3(N-1)+1)(M-1)+N-1
= (3N-3+1)(M-1)+N-1
= (3N-2)(M-1)+N-1
= 3NM-3N-2M+2+N-1
= 3NM-2N-2M+1
= your formula
Deploy the... I think it's a yellow button... it's usually flashing... it makes the engines go... WHOOSH!