There is a game dungeon comprised of n x n rooms arranged in a grid.
You are given a 2D array fruits of size n x n, where fruits[i][j]
represents the number of fruits in the room (i, j). Three children will play in the game dungeon, with initial positions at the corner rooms (0, 0),
(0, n - 1), and (n - 1, 0).
The children will make exactlyn - 1 moves according to the following rules to reach the room (n - 1, n - 1):
The child starting from (0, 0) must move from their current room (i, j) to one of the rooms (i + 1, j + 1), (i + 1, j), and (i, j + 1) if the target room exists.
The child starting from (0, n - 1) must move from their current room (i, j) to one of the rooms (i + 1, j - 1), (i + 1, j), and (i + 1, j + 1) if the target room exists.
The child starting from (n - 1, 0) must move from their current room (i, j) to one of the rooms (i - 1, j + 1), (i, j + 1), and (i + 1, j + 1) if the target room exists.
When a child enters a room, they will collect all the fruits there. If two or more children enter the same room, only one child will collect the fruits, and the room will be emptied after they leave.
Return the maximum number of fruits the children can collect from the dungeon.
Input: fruits =[[1,1],[1,1]]Output: 4Explanation:
In this example:* The 1st child moves on the path `(0,0) -> (1,1)`.* The 2nd child moves on the path `(0,1) -> (1,1)`.* The 3rd child moves on the path `(1,0) -> (1,1)`.In total they collect `1 + 1 + 1 + 1 = 4` fruits.
Each child starts from a different corner and must reach the bottom-right corner in exactly n-1 moves, collecting fruits along the way. Since children can overlap, we need to avoid double-counting fruits. We can use dynamic programming to track the maximum fruits collected for each possible position of the three children at each step.
Let dp[i][j][k] be the maximum fruits collected when:
Child 1 is at (i, j)
Child 2 is at (i, n-1-(j-i))
Child 3 is at (n-1-(j-i), j)
All have taken the same number of steps (i+j)
For each move, try all possible next moves for each child, and update the DP accordingly, making sure not to double-count fruits if two or more children land on the same cell.
The answer is the maximum value at the destination cell after n-1 moves.
classSolution:
defmaximumFruits(self, fruits: list[list[int]]) -> int:
n = len(fruits)
from collections import defaultdict
dp = defaultdict(lambda: -1)
dp[(0,0,0)] = fruits[0][0] + fruits[0][n-1] + fruits[n-1][0]
for step in range(1, n):
ndp = defaultdict(lambda: -1)
for i,j,k in dp:
for di in (0,1):
ni = i+di
if ni>=n: continuefor dj in (0,1):
nj = j+dj
if nj>=n: continuefor dk in (0,1):
nk = k+dk
if nk>=n: continue pos = {(ni,ni),(nj,n-1-(nj-ni)),(n-1-(nk-nj),nk)}
add = sum(fruits[x][y] for x,y in pos)
ndp[(ni,nj,nk)] = max(ndp[(ni,nj,nk)], dp[(i,j,k)]+add)
dp = ndp
return dp[(n-1,n-1,n-1)]
1
// Omitted for brevity due to high complexity and memory usage
1
// Omitted for brevity due to high complexity and memory usage