There is an grid in which there are rows and colums. A cell is defined as the row from the top and column from left. You are located at initially and can perform the following steps any number of times:
- You can move any number of steps downwards.
- You can move any number of steps towards the right.
There are some obstacles in the path.
You are initially located at and wants to reach but you are interested in knowing the number of ways you can reach from . Since these numbers can huge, print it modulo .
Two ways are considered different if they have a different number of steps or differ in some positions.
Example:
Input: n=3,m=3,grid[][]={{.,.,.},{.,*,.},{.,.,.}};
Output: 8
Approach
Java
public class NumberOfWays {// define mode valuesfinal static long mod = (long) (1e9 + 7);public static void main(String args[]) {int n = 3;int m = 3;char grid[][] = { { '.', '.', '.' }, { '.', '*', '.' }, { '.', '.', '.' } };long dp[][] = new long[n][m];long sumrow[] = new long[n];long sumcol[] = new long[m];for (int i = 0; i < n; i++)for (int j = 0; j < m; j++) {if (grid[i][j] == '*')dp[i][j] = 0;else if (i == 0 && j == 0)dp[i][j] = 1;else if (i == 0)dp[i][j] = sumrow[i];else if (j == 0)dp[i][j] = sumcol[j];elsedp[i][j] = (sumcol[j] + sumrow[i]) % mod;if (dp[i][j] == 0) {sumrow[i] = 0;sumcol[j] = 0;} else {sumrow[i] = (sumrow[i] + dp[i][j]) % mod;sumcol[j] = (sumcol[j] + dp[i][j]) % mod;}}System.out.println(dp[n - 1][m - 1]);}}
No comments:
Post a Comment