VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-points-top-left-matrix-bottom-right-return-back/

⇱ Collect Maximum Number of Diamonds - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collect Maximum Number of Diamonds

Last Updated : 19 Jun, 2026

Given a square matrix mat[][] of size n × n containing values -1, 0, and 1 having the following meanings:

  • -1 represents a blocked cell that cannot be visited.
  • 0 represents an empty cell through which movement is allowed.
  • 1 represents a cell containing a diamond.

Start from (0, 0), move to (n - 1, n - 1) using only right and down moves, and then return back to (0, 0) using only left and up moves. Whenever a cell containing a diamond is visited, it is collected, and each diamond can be collected only once. Find the maximum number of diamonds that can be collected. If no valid path exists, return -1.

Note: The matrix uses 0-based indexing.

Examples:

Input: mat[][] = {{0, 1, 0},{1, -1, 1},{0, 1, 0}}
Output: 4
Explanation: The path from (0, 0) to (n - 1, n - 1) and back collects diamonds without double counting, giving a total of 4.

👁 2056958366

Input: mat[][] = {{0, 0, 0},{0, -1, 0},{0, 0, 0}}
Output: 0
Explanation: A valid round trip exists, but no diamonds are present in the matrix.

👁 2056958367

Input: mat[][] = {{1,-1},{-1, 1}}
Output: -1
Explanation: No valid path exists from (0, 0) to (n - 1, n - 1).

👁 2056958368

[Expected Approach] Using Two-Path Dynamic Programming - O(n^3) Time and O(n^3) Space

A direct simulation of moving from (0, 0) to (n - 1, n - 1) and then returning back to (0, 0) is difficult because it becomes hard to track visited cells and ensure that each diamond is collected only once.

Instead of simulating the backward journey separately, we use the fact that moving left and up is just the reverse of moving right and down. So, the problem is transformed into a two-path dynamic programming approach where both paths start from (0, 0) and move simultaneously towards (n - 1, n - 1).

  • Start two paths from (0, 0) and move both towards (n - 1, n - 1).
  • At any point, the positions are (r1, c1) and (r2, c2).
  • Since both paths take the same number of steps: r1 + c1 = r2 + c2, so c2 can be derived.
  • Use a DP state dp[r1][c1][r2] to store the maximum diamonds collected.
  • From each state, try all possible moves: Down-Down, Down-Right, Right-Down, and Right-Right.
  • If both paths are on the same cell, count the diamond only once.
  • Use memoization to avoid repeating the same calculations.
  • The final answer is obtained when both paths reach (n - 1, n - 1).

Output
4
Comment
Article Tags: