2120. Execution of All Suffix Instructions Staying in a Grid (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class Solution:
    def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
        m = len(s)
        result = [0] * m
        for i in range(m):
            a, b = startPos
            for j in range(i, m):
                c = s[j]
                if c == "L":
                    b -= 1
                elif c == "R":
                    b += 1
                elif c == "U":
                    a -= 1
                else:
                    a += 1
                if 0 <= a < n and 0 <= b < n:
                    result[i] += 1
                else:
                    break
        return result