You can use the grid structure:
The number of paths from one corner to another on a square grid is determined by the grid size of the Pascal triangle: (x+y) choose x
Each path must cross exactly one point on each diagonal.
Take all the points on the diagonal passing through the inner corner, calculate the number of paths through each and summarize.
This leads to the O(min(pa, qb)) algorithm, which assumes constant arithmetic.
In your case: (two paths to the center) * (two paths from the center) + (one path in the corner) = (four paths in the center) + (one path in the corner) = (five paths)
+-+-+ | | | +-+-A-+-+ | | | | | +-B-+-+-+ | | | | | C-+-+-+-+ | | | | | +-+-+-+-+ (1+2) choose 1 * (2+3) choose 2 (through A) + (2+1) choose 2 * (3+2) choose 3 (through B) + (3+0) choose 3 * (4+1) choose 4 (through C) = 3 choose 1 * 5 choose 2 + 3 choose 2 * 5 choose 3 + 3 choose 3 * 5 choose 4 = 3*10 + 3*10 + 1*5 = 30+30+5 = 65 paths
source share