


Consider the maze below :
0 0 0
0 -1 0
0 0 0
There are two ways to reach the bottom left corner -
(1, 1) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
(1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
Hence the answer for the above test case is 2.
The first line contains a single integer ‘T’ denoting the number of test cases. Then each test case follows.
The first line of each test case contains integers ‘N’ and ‘M’ representing the size of the input grid.
Then ‘N’ lines follow, each of which contains ‘M’ space-separated integers denoting the elements of the matrix.
For each test case print an integer denoting the number of ways to reach the bottom right corner from the top-left corner modulo 10^9 + 7.
Output for each test case will be printed in a separate line.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= N,M <= 200
Note: It is guaranteed that the top-left cell does not have an obstacle.
Time Limit: 1 sec
We can observe that we can reach cell (i, j) only through two cells if they exist -
(i - 1, j) and (i, j - 1). Also if the cell (i, j) is blocked we can simply calculate the number of ways to reach it as zero.
So if we know the number of ways to reach cell (i - 1, j) and (i, j - 1) we can simply add these two to get the number of ways to reach cell (i, j).
Let paths(i, j) be the number of ways to reach cell (i, j).
So our recursive relation can be defined as follows:
paths(i, j) = 0 if cell is blocked or invalid.
paths(i, j) = paths(i - 1, j) + (i, j -1) otherwise.
O(2^(N + M)) Where N and M are dimensions of the input matrix.
For every cell, we are making two recursive calls with the length of the path decreasing by one. Hence the time complexity becomes O(2^(N + M)).
We can observe that we are calculating the same value, again and again, using recursion.
For example paths(2, 3) and paths(3, 2) will both use paths(2, 2) which is being calculated separately twice. We can save this time by using dynamic programming and saving the results for previous paths. We memoize the results so that we can use them in the next call.
We can observe that we are calculating the same value, again and again, using recursion.
For example paths(2, 3) and paths(3, 2) will both use paths(2, 2) which is being calculated separately twice. We can save this time by using dynamic programming and saving the results for previous paths.