소프트웨어에 대한 모든 것

LeetCode 풀기 - 2120. Execution of All Suffix Instructions Staying in a Grid 본문

알고리즘/LeetCode

LeetCode 풀기 - 2120. Execution of All Suffix Instructions Staying in a Grid

앤테바 2022. 3. 10. 21:41
반응형

2120. Execution of All Suffix Instructions Staying in a Grid

https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid/

 

Execution of All Suffix Instructions Staying in a Grid - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제)

솔루션1) brute force

시간복잡도 : O(N^2)

class Solution:
    def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
        dirs = {
            'U': [-1, 0],
            'D': [1, 0],
            'L': [0, -1],
            'R': [0, 1],
        }
        
        res = []
        for i in range(len(s)):
            cur_pos = startPos.copy()
            move_cnt = 0
            for j in range(i, len(s)):
                cur_pos[0] += dirs[s[j]][0] 
                cur_pos[1] += dirs[s[j]][1] 
                
                if (0 <= cur_pos[0] < n) and (0 <= cur_pos[1] < n):
                    move_cnt += 1
                else:
                    break
            res.append(move_cnt)
        return res

 

반응형
Comments