Reading the Problem
The problem roughly says: a cow moves around inside a rectangle of a given size. The cells are either grass or trees, and the cow cannot walk on trees.
In one move, the cow can go up, down, left, or right, but cannot stay in place (though it can go in circles!). Given two points A and B, count the number of paths from A to B that take exactly T steps.
There’s a slight issue with the original problem statement—maybe it’s a translation problem. The original text says “within T seconds,” but what it actually wants is exactly that T-th second. It took me forever to find the bug; I only noticed it after checking the discussion board.
Approach
At first I thought of using BFS, searching until the front element’s time reaches t+1. But trying it gave MLE, and I didn’t feel like optimizing with memoization or anything.
Then it hit me: the number of ways to reach each cell at each moment is like a “slice,” and the recurrence between different times and coordinates is obvious. The number of paths at a given time equals the sum of the path counts from the four neighboring cells at the previous time. Of course, if the cell is a tree, it’s 0. From this, we can write the DP formula:
$$
dp[x][y][t] =
\begin{cases}
0 & \text{if } \text{block}[x][y] = 1 \
dp[x-1][y][t-1] + dp[x+1][y][t-1] + dp[x][y-1][t-1] + dp[x][y+1][t-1] & \text{otherwise}
\end{cases}
$$
AC Code
1 |
|