Ctrl K

Berry Field Round Trip

Hard
An n × n field is given as a matrix field, where each cell holds one of three values: - 0: an empty cell you can walk through; - 1: a cell with a berry, which you can pick before moving on; - -1: a rock that cannot be crossed. A picker starts at the top-left corner (0, 0), walks to the bottom-right corner (n - 1, n - 1) stepping only right or down, then walks back to (0, 0) stepping only left or up. Only rock-free cells can be used. Whenever the picker passes a cell with a berry, the berry is picked and the cell becomes empty, so it cannot be picked a second time. Return the largest number of berries the round trip can collect. If the bottom-right corner cannot be reached at all, return 0.
Example 1
field=[[1, 0, 1], [0, -1, 1], [1, 1, 1]] → 6

Go there along the top and right edges for 4 berries and come back along the bottom and left edges for 2 more, skirting the rock in the middle: all 6 berries on the field are collected.

Example 2
field=[[0, -1], [-1, 1]] → 0

Rocks block both ways to the far corner, so nothing can be collected.

Example 3
field=[[1]] → 1
Constraints
  • 1 ≤ n ≤ 50
  • len(field) = len(field[i]) = n
  • field[i][j] ∈ {-1, 0, 1}
  • field[0][0] ≠ -1, field[n-1][n-1] ≠ -1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Solid Panel Block HardCrossing the Cave HardLongest Uphill Walk HardWeeks of Rest by Flight HardSix-Cell Tile Slider Hard
loading Python…
Input
field=[[1, 0, 1], [0, -1, 1], [1, 1, 1]]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 79 tests on the server, hidden ones included.