Code Explanation:
1. Function Definition
def count_paths(m, n):
Defines a function count_paths that takes two arguments m (rows) and n (columns), representing the size of the grid.
2. Initialize the DP Table
dp = [[1]*n for _ in range(m)]
Creates a 2D list (matrix) dp with m rows and n columns.
Each cell is initialized to 1 because:
There is only 1 way to reach any cell in the first row (move right only).
There is only 1 way to reach any cell in the first column (move down only).
3. Calculate Paths for Remaining Cells
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
Loops through all cells starting from row 1 and column 1 (skipping the first row and first column).
Updates each cell dp[i][j] with the sum of:
dp[i-1][j]: number of ways to reach the cell above.
dp[i][j-1]: number of ways to reach the cell to the left.
This works because you can only move right or down, so the total ways to reach dp[i][j] is the sum of ways to reach from above and from the left.
4. Return the Result
return dp[-1][-1]
Returns the value in the bottom-right cell of the matrix (dp[m-1][n-1]), which is the total number of unique paths to reach the bottom-right corner.
5. Function Call and Output
print(count_paths(3, 4))
Calls count_paths with a 3x4 grid.
Output is 10, meaning there are 10 unique paths from the top-left to the bottom-right corner moving only right or down.
Final Output:
10
.png)

0 Comments:
Post a Comment