## In a sliding game a counter may slide horizontally or vertically into an empty space. The objective of the game is to move the red counter from the top left corner of a grid to the bottom right corner; the space always starts in the bottom right corner. For example, the following sequence of pictures show how the game can be completed in five moves on a $2$ by $2$ grid.

Let $S(m,n)$ represent the minimum number of moves to complete the game on an $m$ by $n$ grid. For example, it can be verified that $S(5,4) = 25$.

There are exactly $5482$ grids for which $S(m,n) = p^2$, where $p \lt 100$ is prime.

How many grids does $S(m,n) = p^2$, where $p \lt 10^6$ is prime?

### To solve this problem, we can use dynamic programming to calculate the minimum number of moves required to complete the game on an m by n grid.

Let’s define a function `min_moves(m, n)` which returns the minimum number of moves to complete the game on an m by n grid.

1. Start by creating an empty two-dimensional array, `dp`, of size (m+1) by (n+1) to store the minimum moves for each subproblem.

2. Initialize `dp[1][1]` to 0, as it takes 0 moves to reach the starting position.

3. Iterate over the rows starting from 1 to m, and within each row, iterate over the columns starting from 1 to n.

4. For each cell dp[i][j], calculate the minimum moves required to reach that cell based on the adjacent cells.

– If i == 1 and j == 1, continue to the next iteration as we have already initialized it with 0.

– If j == 1, dp[i][j] = dp[i-1][j] + i-1 (as we can only move vertically from the previous row).

– If i == 1, dp[i][j] = dp[i][j-1] + j-1 (as we can only move horizontally from the previous column).

– Otherwise, take the minimum of dp[i-1][j] + i-1 (moving vertically from the top) and dp[i][j-1] + j-1 (moving horizontally from the left).

5. Finally, return dp[m][n] as the minimum number of moves to complete the game on an m by n grid.

Now, we can iterate over different grid sizes, calculate the minimum moves, and count the number of grids where S(m, n) is a prime square less than 10^6.

“`python

def is_prime(n):

if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def count_grids():
count = 0
for m in range(1, 10**3):
for n in range(1, 10**3):
moves = min_moves(m, n)
if is_prime(moves) and moves < 10**6:
count += 1
return count
def min_moves(m, n):
dp = [[0] * (n+1) for _ in range(m+1)]
dp[1][1] = 0
for i in range(1, m+1):
for j in range(1, n+1):
if i == 1 and j == 1:
continue
if j == 1:
dp[i][j] = dp[i-1][j] + i-1
elif i == 1:
dp[i][j] = dp[i][j-1] + j-1
else:
dp[i][j] = min(dp[i-1][j] + i-1, dp[i][j-1] + j-1)
return dp[m][n]
count = count_grids()
print(count)
```
This code will calculate the number of grids where S(m, n) = p^2, where p < 10^6 is prime. Note that the `is_prime` function is used to check if a number is prime or not.

##### More Answers:

Integer LaddersNim Square

Biclinic Integral Quadrilaterals