[Zhengqing] [1894] 985's Grid Challenge

Problem Description

985的方格难题
Time limit: 1 SecMemory limit: 128 MB

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

1
2
3
2
2 1 2
2 2 2

Sample Output

1
2
1
-1

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).

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<stdio.h>
int map[32][32];
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n,x,y;
		scanf("%d %d %d",&n,&x,&y);
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=n; j++) {
				if(i==x&&j==y)
					map[i][j]=0;
				else {
					if(i==1)
						if(j==1)
							map[i][j]=1;
						else
							map[i][j]=map[i][j-1];
					else if(j==1)
						map[i][j]=map[i-1][j];
					else
						map[i][j]=(map[i-1][j]+map[i][j-1])%1000000007;
				}
			}
		}
		printf("%d\n",map[n][n]==0?-1:map[n][n]);
	}
	return 0;
}

Problem link:[ZZULI][1894]985’s Grid Puzzle

Loading...