Code Explanation:
Step 1: Base Case
if m == 1 or n == 1:
return 1
If either m == 1 or n == 1, there's only one way to reach the destination: go straight down or straight right, respectively.
So, return 1 in this case.
Step 2: Recursive Case
return count_paths(m - 1, n) + count_paths(m, n - 1)
If you're not at the edge of the grid, the total paths are the sum of:
All paths by going down (reduce m by 1),
All paths by going right (reduce n by 1).
Step 3: Trace count_paths(3, 3)
Let’s calculate count_paths(3, 3) recursively:
count_paths(3, 3)
= count_paths(2, 3) + count_paths(3, 2)
= (count_paths(1, 3) + count_paths(2, 2)) + (count_paths(2, 2) + count_paths(3, 1))
= (1 + (count_paths(1, 2) + count_paths(2, 1))) + ((count_paths(1, 2) + count_paths(2, 1)) + 1)
= (1 + (1 + 1)) + ((1 + 1) + 1)
= (1 + 2) + (2 + 1)
= 3 + 3 = 6
Final Answer:
print(count_paths(3, 3)) # Output: 6
There are 6 unique paths in a 3×3 grid from top-left to bottom-right moving only right or down.
Final Output:
6
.png)

0 Comments:
Post a Comment