返回介绍

solution / 2100-2199 / 2120.Execution of All Suffix Instructions Staying in a Grid / README_EN

发布于 2024-06-17 01:03:09 字数 9489 浏览 0 评论 0 收藏 0

2120. Execution of All Suffix Instructions Staying in a Grid

中文文档

Description

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.

 

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 ith instruction:
- 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid.
- 1st:  "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1).
- 2nd:   "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0).
- 3rd:  "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0).
- 4th:   "LU". Only one instruction "L" can be executed before it moves off the grid.
- 5th:    "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:
- 0th: "LURD".
- 1st:  "URD".
- 2nd:   "RD".
- 3rd:  "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 <= startrow, startcol < n
  • s consists of 'L', 'R', 'U', and 'D'.

Solutions

Solution 1

class Solution:
  def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
    ans = []
    m = len(s)
    mp = {"L": [0, -1], "R": [0, 1], "U": [-1, 0], "D": [1, 0]}
    for i in range(m):
      x, y = startPos
      t = 0
      for j in range(i, m):
        a, b = mp[s[j]]
        if 0 <= x + a < n and 0 <= y + b < n:
          x, y, t = x + a, y + b, t + 1
        else:
          break
      ans.append(t)
    return ans
class Solution {
  public int[] executeInstructions(int n, int[] startPos, String s) {
    int m = s.length();
    int[] ans = new int[m];
    Map<Character, int[]> mp = new HashMap<>(4);
    mp.put('L', new int[] {0, -1});
    mp.put('R', new int[] {0, 1});
    mp.put('U', new int[] {-1, 0});
    mp.put('D', new int[] {1, 0});
    for (int i = 0; i < m; ++i) {
      int x = startPos[0], y = startPos[1];
      int t = 0;
      for (int j = i; j < m; ++j) {
        char c = s.charAt(j);
        int a = mp.get(c)[0], b = mp.get(c)[1];
        if (0 <= x + a && x + a < n && 0 <= y + b && y + b < n) {
          x += a;
          y += b;
          ++t;
        } else {
          break;
        }
      }
      ans[i] = t;
    }
    return ans;
  }
}
class Solution {
public:
  vector<int> executeInstructions(int n, vector<int>& startPos, string s) {
    int m = s.size();
    vector<int> ans(m);
    unordered_map<char, vector<int>> mp;
    mp['L'] = {0, -1};
    mp['R'] = {0, 1};
    mp['U'] = {-1, 0};
    mp['D'] = {1, 0};
    for (int i = 0; i < m; ++i) {
      int x = startPos[0], y = startPos[1];
      int t = 0;
      for (int j = i; j < m; ++j) {
        int a = mp[s[j]][0], b = mp[s[j]][1];
        if (0 <= x + a && x + a < n && 0 <= y + b && y + b < n) {
          x += a;
          y += b;
          ++t;
        } else
          break;
      }
      ans[i] = t;
    }
    return ans;
  }
};
func executeInstructions(n int, startPos []int, s string) []int {
  m := len(s)
  mp := make(map[byte][]int)
  mp['L'] = []int{0, -1}
  mp['R'] = []int{0, 1}
  mp['U'] = []int{-1, 0}
  mp['D'] = []int{1, 0}
  ans := make([]int, m)
  for i := 0; i < m; i++ {
    x, y := startPos[0], startPos[1]
    t := 0
    for j := i; j < m; j++ {
      a, b := mp[s[j]][0], mp[s[j]][1]
      if 0 <= x+a && x+a < n && 0 <= y+b && y+b < n {
        x += a
        y += b
        t++
      } else {
        break
      }
    }
    ans[i] = t
  }
  return ans
}
function executeInstructions(n: number, startPos: number[], s: string): number[] {
  const m = s.length;
  const ans = new Array(m);
  for (let i = 0; i < m; i++) {
    let [y, x] = startPos;
    let j: number;
    for (j = i; j < m; j++) {
      const c = s[j];
      if (c === 'U') {
        y--;
      } else if (c === 'D') {
        y++;
      } else if (c === 'L') {
        x--;
      } else {
        x++;
      }
      if (y === -1 || y === n || x === -1 || x === n) {
        break;
      }
    }
    ans[i] = j - i;
  }
  return ans;
}
impl Solution {
  pub fn execute_instructions(n: i32, start_pos: Vec<i32>, s: String) -> Vec<i32> {
    let s = s.as_bytes();
    let m = s.len();
    let mut ans = vec![0; m];
    for i in 0..m {
      let mut y = start_pos[0];
      let mut x = start_pos[1];
      let mut j = i;
      while j < m {
        match s[j] {
          b'U' => {
            y -= 1;
          }
          b'D' => {
            y += 1;
          }
          b'L' => {
            x -= 1;
          }
          _ => {
            x += 1;
          }
        }
        if y == -1 || y == n || x == -1 || x == n {
          break;
        }
        j += 1;
      }
      ans[i] = (j - i) as i32;
    }
    ans
  }
}
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* executeInstructions(int n, int* startPos, int startPosSize, char* s, int* returnSize) {
  int m = strlen(s);
  int* ans = malloc(sizeof(int) * m);
  for (int i = 0; i < m; i++) {
    int y = startPos[0];
    int x = startPos[1];
    int j = i;
    for (j = i; j < m; j++) {
      if (s[j] == 'U') {
        y--;
      } else if (s[j] == 'D') {
        y++;
      } else if (s[j] == 'L') {
        x--;
      } else {
        x++;
      }
      if (y == -1 || y == n || x == -1 || x == n) {
        break;
      }
    }
    ans[i] = j - i;
  }
  *returnSize = m;
  return ans;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文