Code Explanation:
1. Function Definition
def count_paths(r, c):
This defines a function named count_paths that takes two parameters:
r: number of rows
c: number of columns
2. Base Case: Grid size is 0
if r == 0 or c == 0:
return 0
If either r or c is 0, it means there's no grid (invalid), so there are 0 paths.
This is an edge case guard to avoid negative recursion or invalid grids.
3. Base Case: At destination
if r == 1 and c == 1:
return 1
This checks if you're at the starting point, which is also the destination in a 1x1 grid.
In this case, there's exactly 1 path — you’re already there.
This acts as the stopping condition for the recursion.
4. Recursive Case: Count from top and left
return count_paths(r - 1, c) + count_paths(r, c - 1)
This is the heart of the recursive logic.
To reach cell (r, c), you could have come:
from the cell above: (r-1, c)
from the cell to the left: (r, c-1)
So, total paths = paths from top + paths from left.
5. Function Call
print(count_paths(3, 3))
This calls the function with r = 3, c = 3 and prints the result.
It calculates the number of unique paths in a 3×3 grid.
Output Explanation
Let’s trace what count_paths(3, 3) does:
It breaks into:
count_paths(2, 3) + count_paths(3, 2)
Each of these breaks down similarly, and eventually reaches the base case (1,1) multiple times. After full recursion, the number of unique paths = 6.
Final Output:
6


0 Comments:
Post a Comment