Problem Description
Description
985 has entered an n * n grid map, and he already knows that one cell in it is broken. Now he wants to go from (1, 1) to (n, n), moving only one step down or right each time. Can he reach (n, n)? If he cannot reach it, output -1; otherwise, output the number of ways to reach (n, n).
Input
The first line contains an integer t, representing t test cases.
The first line of each test case contains three integers n, x, and y, representing the size of the grid map and the position of the broken cell.
Note: 1 <= t <= 20, 1 <= n <= 30, 1 <= x, y <= n.
Output
If (n, n) is reachable, output the number of ways modulo 1e9 + 7; otherwise, output -1.
Sample Input
| |
Sample Output
| |
Problem Analysis
Solution 1: Consider DP, where dp[i][j] represents the number of ways to reach position (i, j),
dp[i][j] = -1 means the position has not been visited, so a brute-force transition is enough.
Time complexity: O(T * n * n).
Solution 2: Ignoring the broken cell for now, the number of ways from (1, 1) to each position is some combination number in Pascal’s triangle.
Moreover, the number of ways to reach position (n, m) is C(n + m - 2, m - 1).
Let ans[1][1][n][m] be the number of ways from (1, 1) to (n, m).
Then the result is ans[1][1][n][n] - ans[1][1][x][y] * ans[x][y][n][n]. To avoid mistakes, use the Modular Inverse.
Time complexity: O(T * log(1e9 + 5)^4).
| |
Problem link:[ZZULI][1894]985’s Grid Puzzle