Problem · Matrix

Trace an Eight-Direction Robot Until Blocked

Learn this problem
EasyPinterest logoPinterestFULLTIMEPHONE SCREEN

Problem statement

The integer matrix grid contains open cells marked 0 and blockers marked -1. A robot starts at the open coordinate start. The array moves is an ordered list of unit directions, where each direction is one of the eight combinations [dr, dc] with dr and dc in {-1, 0, 1} and not both zero.

Mark the starting cell and every open cell the robot enters as 1. Process the moves in order. If the next move would leave the matrix or enter a blocker, stop immediately and ignore all remaining moves. Entering a cell already marked 1 is allowed.

Return the final matrix. Blockers remain -1.

Function

traceRobot(grid: int[][], start: int[], moves: int[][]) → int[][]

Examples

Example 1

grid = [[0,0,0],[0,-1,0],[0,0,0]]start = [2,0]moves = [[-1,0],[0,1],[0,1],[1,1]]return = [[0,0,0],[1,-1,0],[1,0,0]]

The first move marks [1,0]. The next move would enter the blocker at [1,1], so the robot stops.

Example 2

grid = [[0,0],[0,0]]start = [0,0]moves = [[0,1],[1,0],[0,-1],[-1,0]]return = [[1,1],[1,1]]

The four moves visit every cell and return to the start.

Constraints

  • 1 <= grid.length, grid[i].length <= 200.
  • All rows have equal length and initially contain only 0 and -1.
  • start identifies an open cell.
  • 0 <= moves.length <= 200000.
  • Every move is one of the eight valid unit directions.

More Pinterest problems

drafts saved locally
public int[][] traceRobot(int[][] grid, int[] start, int[][] moves) {
    // Write your code here.
}
grid[[0,0,0],[0,-1,0],[0,0,0]]
start[2,0]
moves[[-1,0],[0,1],[0,1],[1,1]]
expected[[0,0,0],[1,-1,0],[1,0,0]]
checking account