0

Given a grid of m*n where each cell contains either 0 or 1. 0 means obstacle, you cannot pass through a cell with 0. We have to find a path from (0,0) to (m,n) that has the maximum number of ones. Allowed moves are right, left, bottom(down). If there is no such path return -1. You cannot pass through the same cell twice. Contraints: 1<=m,n<=400.

I couldn't think of any approach other than brute force by listing all valid paths. I want optimized approach and solution.

bguiz
  • 27,371
  • 47
  • 154
  • 243
heisenberg
  • 11
  • 1

1 Answers1

0

Once we have descended to a row, we can choose to either go right or go left and we cannot go back after choosing that direction. So for each cell calculate the optimal solution for each of those states and choose the best. Let dp[y][x][r] represent the optimal solution at cell (y, x), where r is 0 if we're going left on the row, and 1 if we're going right on the row. Then generally,

dp[y][x][0] =
  -Infinity if grid[y][x] == 0 else 1 + max(
    dp[y-1][x][0],
    dp[y-1][x][1],
    dp[y][x+1][0]
)

dp[y][x][1] =
  -Infinity if grid[y][x] == 0 else 1 + max(
    dp[y-1][x][0],
    dp[y-1][x][1],
    dp[y][x-1][1]
)

I'll leave it to the reader to work out base cases and how to pick the cell containing the solution.

גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61