|
| 1 | +/** |
| 2 | + * 2120. Execution of All Suffix Instructions Staying in a Grid |
| 3 | + * https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at |
| 7 | + * (n - 1, n - 1). You are given the integer n and an integer array startPos where |
| 8 | + * startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol). |
| 9 | + * |
| 10 | + * You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the |
| 11 | + * robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down). |
| 12 | + * |
| 13 | + * The robot can begin executing from any ith instruction in s. It executes the instructions one |
| 14 | + * by one towards the end of s but it stops if either of these conditions is met: |
| 15 | + * - The next instruction will move the robot off the grid. |
| 16 | + * - There are no more instructions left to execute. |
| 17 | + * |
| 18 | + * Return an array answer of length m where answer[i] is the number of instructions the robot can |
| 19 | + * execute if the robot begins executing from the ith instruction in s. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number} n |
| 24 | + * @param {number[]} startPos |
| 25 | + * @param {string} s |
| 26 | + * @return {number[]} |
| 27 | + */ |
| 28 | +var executeInstructions = function(n, startPos, s) { |
| 29 | + const m = s.length; |
| 30 | + const result = new Array(m).fill(0); |
| 31 | + |
| 32 | + for (let i = 0; i < m; i++) { |
| 33 | + let row = startPos[0]; |
| 34 | + let col = startPos[1]; |
| 35 | + let steps = 0; |
| 36 | + |
| 37 | + for (let j = i; j < m; j++) { |
| 38 | + if (s[j] === 'L') col--; |
| 39 | + else if (s[j] === 'R') col++; |
| 40 | + else if (s[j] === 'U') row--; |
| 41 | + else row++; |
| 42 | + |
| 43 | + if (row < 0 || row >= n || col < 0 || col >= n) break; |
| 44 | + steps++; |
| 45 | + } |
| 46 | + |
| 47 | + result[i] = steps; |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | +}; |
0 commit comments