Dynamic Programming21 sections · 916 units
Open in Course

Out of Boundary - Transition

Four directions

From (r,c)(r, c) with kk moves, you can go up, down, left, or right. The formula: dp[r][c][k]=dp[r1][c][k1]+dp[r+1][c][k1]+dp[r][c1][k1]+dp[r][c+1][k1]dp[r][c][k] = dp[r-1][c][k-1] + dp[r+1][c][k-1] + dp[r][c-1][k-1] + dp[r][c+1][k-1] Base case: if (r,c)(r, c) is outside the grid, return 11. That path successfully left.

If k=0k = 0 and you're still inside, return 00. No moves left, didn't escape. Don't forget: take results modulo 109+710^9 + 7 since counts can get huge. Each cell receives probability from its four neighbors. The grid acts like a probability distribution over positions.