741.cc 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #include <iostream>
  2. #include <vector>
  3. using std::vector;
  4. using std::cout; using std::endl;
  5. class Solution {
  6. public:
  7. int cherryPickup(vector<vector<int>>& grid) {
  8. int n = grid.size();
  9. int dp[2 * n - 1][n][n];
  10. memset(dp, 0xFF, sizeof(dp));
  11. dp[2 * n - 2][n - 1][n - 1] = 0;
  12. dp[0][0][0] = grid[0][0];
  13. for (int k = 1; k < 2 * n - 1; k++) {
  14. for (int x1 = 0; x1 <= k && x1 < n; x1++) {
  15. for (int x2 = 0; x2 <= k && x2 < n; x2++) {
  16. int y1 = k - x1, y2 = k - x2;
  17. // current coordinate is rock
  18. if (grid[x1][y1] == -1 || grid[x2][y2] == -1) continue;
  19. for (int i = 0; i < 4; i++) {
  20. int x1_ = x1 + dx1[i], x2_ = x2 + dx2[i];
  21. int y1_ = k - 1 - x1_, y2_ = k - 1 - x2_;
  22. // previous coordinate is not valid
  23. if (x1_ < 0 || x2_ < 0 || y1_ < 0 || y2_ < 0) continue;
  24. // previous coordinate is rock
  25. if (grid[x1_][y1_] == -1 || grid[x2_][y2_] == -1) continue;
  26. // previous state is not reachable
  27. if (dp[k - 1][x1_][x2_] == -1) continue;
  28. int delta = x1 == x2 ? grid[x1][y1] : grid[x1][y1] + grid[x2][y2];
  29. dp[k][x1][x2] = std::max(dp[k][x1][x2], dp[k - 1][x1_][x2_] + delta);
  30. }
  31. }
  32. }
  33. }
  34. return dp[2 * n - 2][n - 1][n - 1];
  35. }
  36. private:
  37. int dx1[4] = {0, -1, 0, -1};
  38. int dx2[4] = {0, 0, -1, -1};
  39. };
  40. // (0, 0) -> (n - 1, n - 1) -> (0, 0) == (0, 0) -> (n - 1, n - 1) 2 times == 2 people start at (0, 0) at the same time
  41. // dp[k][x1][x2] means max cherries from (0, 0) to (x1, y1) and (x2, y2) at k steps
  42. // dp[0][0][0] = grid[0][0]
  43. // dp[k][x1][x2] = max(dp[k - 1][x1][x2] + delta, dp[k - 1][x1 - 1][x2] + delta, dp[k - 1][x1][x2 - 1] + delta, dp[k - 1][x1 - 1][x2 - 1] + delta)
  44. int main() {
  45. Solution* sol = new Solution();
  46. vector<vector<int>> grid = {{0, 1, -1}, {1, 0, -1}, {1, 1, 1}};
  47. cout << "actual: " << sol->cherryPickup(grid) << ", expected: " << 5 << endl;
  48. grid = {{1, 1, -1}, {1, -1, 1}, {-1, 1, 1}};
  49. cout << "actual: " << sol->cherryPickup(grid) << ", expected: " << 0 << endl;
  50. return 0;
  51. }