Formatted question description: https://leetcode.ca/all/2120.html

# 2120. Execution of All Suffix Instructions Staying in a Grid (Medium)

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 integer `n`

and an integer array `startPos`

where `startPos = [start`

indicates that a robot is initially at cell _{row}, start_{col}]`(start`

._{row}, start_{col})

You are also given a **0-indexed** string `s`

of length `m`

where `s[i]`

is the `i`

instruction for the robot: ^{th}`'L'`

(move left), `'R'`

(move right), `'U'`

(move up), and `'D'`

(move down).

The robot can begin executing from any `i`

instruction in ^{th}`s`

. It executes the instructions one by one towards the end of `s`

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 length* `m`

*where* `answer[i]`

*is the number of instructions the robot can execute if the robot begins executing from the*

`i`^{th}

*instruction in*

`s`

.

**Example 1:**

Input:n = 3, startPos = [0,1], s = "RRDDLU"Output:[1,5,4,3,1,0]Explanation:Starting from startPos and beginning execution from the i^{th}instruction: - 0^{th}: "RDDLU". Only one instruction "R" can be executed before it moves off the grid. - 1R^{st}: "". All five instructions can be executed while it stays in the grid and ends at (1, 1). - 2RDDLU^{nd}: "". All four instructions can be executed while it stays in the grid and ends at (1, 0). - 3DDLU^{rd}: "". All three instructions can be executed while it stays in the grid and ends at (0, 0). - 4DLU^{th}: "U". Only one instruction "L" can be executed before it moves off the grid. - 5L^{th}: "U". If moving up, it would move off the grid.

**Example 2:**

Input:n = 2, startPos = [1,1], s = "LURD"Output:[4,1,0,0]Explanation:- 0^{th}: "". - 1LURD^{st}: "RD". - 2U^{nd}: "RD". - 3^{rd}: "D".

**Example 3:**

Input:n = 1, startPos = [0,0], s = "LRUD"Output:[0,0,0,0]Explanation:No matter which instruction the robot begins execution from, it would move off the grid.

**Constraints:**

`m == s.length`

`1 <= n, m <= 500`

`startPos.length == 2`

`0 <= start`

_{row}, start_{col}< n`s`

consists of`'L'`

,`'R'`

,`'U'`

, and`'D'`

.

**Similar Questions**:

## Solution 1. Simulation

```
// OJ: https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/
// Time: O(M^2)
// Space: O(1)
class Solution {
public:
vector<int> executeInstructions(int n, vector<int>& start, string s) {
int M = s.size();
auto solve = [&](int i) {
int x = start[0], y = start[1], len = 0;
for (; i < M; ++i, ++len) {
if (s[i] == 'R') ++y;
else if (s[i] == 'L') --y;
else if (s[i] == 'U') --x;
else if (s[i] == 'D') ++x;
if (x < 0 || x >= n || y < 0 || y >= n) return len;
}
return len;
};
vector<int> ans;
for (int i = 0; i < M; ++i) {
ans.push_back(solve(i));
}
return ans;
}
};
```