## Similar Problems

Similar Problems not available

# Number Of Increasing Paths In A Grid - Leetcode Solution

## Companies:

LeetCode: Number Of Increasing Paths In A Grid Leetcode Solution

Difficulty: Hard

Topics: dynamic-programming depth-first-search breadth-first-search matrix array graph

Problem Statement:

Given a two-dimensional integer array grid of size m x n, you need to find out the number of increasing paths from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1). In each step, you can move either right or down to the adjacent cell as long as the cell's value is strictly smaller than the current cell.

Solution:

To solve this problem, we will use dynamic programming. We will create a two-dimensional dp array of size m x n, where dp[i][j] represents the number of increasing paths from the top-left cell (0, 0) to cell (i, j). We will initialize the dp array with 0.

Now, we will fill up the dp array row by row, starting from the top-left corner. For the first row and first column, the number of increasing paths is always 1, because there is only one way to reach those cells. For the rest of the cells, we will calculate the number of increasing paths by adding the number of increasing paths from the cell above and the cell to the left, if the value of those cells is smaller than the current cell.

Here's the code:

int countPaths(vector<vector<int>>& grid) { int m = grid.size(); if (m == 0) return 0; int n = grid[0].size();

```
vector<vector<int>> dp(m, vector<int>(n, 0)); //initialize dp array with 0
//fill up the first row and col of dp array with 1
for (int i = 0; i < m; i++) dp[i][0] = 1;
for (int j = 0; j < n; j++) dp[0][j] = 1;
//fill up the rest of the dp array
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
//add the number of increasing paths from above cell and left cell if their value is smaller
if (grid[i][j] > grid[i - 1][j]) dp[i][j] += dp[i - 1][j];
if (grid[i][j] > grid[i][j - 1]) dp[i][j] += dp[i][j - 1];
}
}
//return the number of increasing paths to the bottom-right cell
return dp[m - 1][n - 1];
```

}

Time Complexity: O(mn), where m is the number of rows and n is the number of columns of the grid.

Space Complexity: O(mn), same as Time complexity as we are using a 2D array of size m x n to store our dynamic programming solution.

## Number Of Increasing Paths In A Grid Solution Code

`1`