1. Recursive 9-Way Branching
Intuition
Recursively explore all 3 moves for robot 1 and 3 moves for robot 2 at each row.
Algorithm
- Define
solve(r, c1, c2). - If
c1 < 0 || c1 >= cols || c2 < 0 || c2 >= cols, return -\infty. - Cherries =
(c1 == c2) ? grid[r][c1] : grid[r][c1] + grid[r][c2]. - If
r == rows - 1, returncherries. - Try all 9 combinations:
dc1 in {-1, 0, 1},dc2 in {-1, 0, 1}. - Return
cherries + max(all 9 next states).
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int r, int c1, int c2, int rows, int cols, const vector<vector<int>>& grid) { if (c1 < 0 || c1 >= cols || c2 < 0 || c2 >= cols) return -1e9; int cherries = (c1 == c2) ? grid[r][c1] : grid[r][c1] + grid[r][c2]; if (r == rows - 1) return cherries; int maxNext = -1e9; for (int dc1 = -1; dc1 <= 1; ++dc1) { for (int dc2 = -1; dc2 <= 1; ++dc2) { maxNext = max(maxNext, solve(r + 1, c1 + dc1, c2 + dc2, rows, cols, grid)); } } return cherries + maxNext; }public: int cherryPickup(vector<vector<int>>& grid) { return solve(0, 0, grid[0].size() - 1, grid.size(), grid[0].size(), grid); }}; int main() { Solution sol; vector<vector<int>> grid = {{3, 1, 1}, {2, 5, 1}, {1, 5, 5}, {2, 1, 1}}; cout << "Max Cherries: " << sol.cherryPickup(grid) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(9^rows) - Space complexity:
O(rows) call stack