Member-only story
Leetcode 2120: Execution of All Suffix Instructions Staying in a Grid
In this Leetcode problem, we are given a start position and a set of instructions. We need to return the number of instructions that are executable if start executing the instructions at each possible position. This is the problem statement:
There is an
n x n
grid, with the top-left cell at(0, 0)
and the bottom-right cell at(n - 1, n - 1)
. You are given the integern
and an integer arraystartPos
wherestartPos = [startrow, startcol]
indicates that a robot is initially at cell(startrow, startcol)
.
You are also given a 0-indexed strings
of lengthm
wheres[i]
is theith
instruction for the robot:'L'
(move left),'R'
(move right),'U'
(move up), and'D'
(move down).
The robot can begin executing from anyith
instruction ins
. It executes the instructions one by one towards the end ofs
but it stops if either of these conditions is met:
The next instruction will move the robot off the grid.
There are no more instructions left to execute.Return an array
answer
of lengthm
whereanswer[i]
is the number of instructions the robot can execute if the robot begins executing from theith
instruction ins
.
It is lengthy, but an example will help understand it really easily:
In this example, we see that we start in the position (0,1)
in a 3*3 grid. The…