Problem · Array

Diagonal Robot Path Sum

Learn this problem
MediumMatroid logoMatroidINTERNOA

Problem statement

You are given a rectangular integer matrix matrix and a starting cell with coordinates (cellX, cellY). Coordinates are zero-based: x is the row index and y is the column index.

A robot starts at (cellX, cellY), initially moving diagonally in direction (+1, +1). It adds the value of every newly visited cell to its sum, including the starting cell.

For each move, first consider the next cell (x + dx, y + dy). If that row would be outside the matrix, reverse dx. If that column would be outside the matrix, reverse dy. Then move one cell using the resulting direction.

The robot stops when it reaches a corner or a cell visited earlier. A corner reached for the first time is included in the sum. A previously visited endpoint is not counted again.

Return the sum collected by the robot. The starting cell is guaranteed not to be a corner.

Function

solution(matrix: int[][], cellX: int, cellY: int) → long

Examples

Example 1

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]cellX = 1cellY = 1return = 14

The robot starts at (1, 1), collecting 5. It next reaches corner (2, 2), collects 9, and stops. The total is 5 + 9 = 14.

Example 2

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]cellX = 1cellY = 1return = 28

The visited cells are (1,1), (2,2), (1,3), and (0,2), contributing 6 + 11 + 8 + 3 = 28. The next move returns to (1,1), so the robot stops without adding that cell twice.

Constraints

  • matrix.length >= 2
  • matrix[row].length == matrix[0].length
  • matrix[0].length >= 2
  • (cellX, cellY) is a valid cell and is not a corner.

More Matroid problems

drafts saved locally
public long solution(int[][] matrix, int cellX, int cellY) {
  // Write your code here.
}
matrix[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
cellX1
cellY1
expected14
checking account