This problem can be solved by GCD easily. But why?
Suppose m<=n, the answer will not be larger than m, and if it is m, we can place all the balls in the first row.
If the ball starts at the first row with column number 0, when it moves back to the first row, its column number will be x, it is satisfied that 2*(n-1)=2*t*(m-1)+2*x, so gcd(x, m-1) = gcd(m-1, n-1), and the distance between two squares can be hit by this ball is gcd(x,m-1).
So the answer cal be calculated by GCD.
Maybe it can be read only by myself. My poor English!
Suppose m<=n, the answer will not be larger than m, and if it is m, we can place all the balls in the first row.
If the ball starts at the first row with column number 0, when it moves back to the first row, its column number will be x, it is satisfied that 2*(n-1)=2*t*(m-1)+2*x, so gcd(x, m-1) = gcd(m-1, n-1), and the distance between two squares can be hit by this ball is gcd(x,m-1).
So the answer cal be calculated by GCD.
Maybe it can be read only by myself. My poor English!