[LeetCode] Execution of All Suffix Instructions Staying in a Grid

2120. Execution of All Suffix Instructions Staying in a Grid

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 = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).

You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: ‘L’ (move left), ‘R’ (move right), ‘U’ (move up), and ‘D’ (move down).

The robot can begin executing from any ith instruction in 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 ith instruction in s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> executeInstructions(int n, vector<int>& p, string s) {
int m = s.length(), y = m + n, x = m + n;
vector<int> Y(y * 2, m), X(x * 2, m);
vector<int> res(m);
for(int i = m - 1; i >= 0; i--) {
Y[y] = X[x] = i;
if(s[i] == 'U') y++;
else if(s[i] == 'D') y--;
else if(s[i] == 'L') x++;
else x--;

res[i] = min({m, Y[y - p[0] - 1], Y[y - p[0] + n], X[x - p[1] - 1], X[x - p[1] + n]}) - i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/04/PS/LeetCode/execution-of-all-suffix-instructions-staying-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.