[LeetCode] 1706. Where Will the Ball Fall

김민우·2022년 12월 16일
0

알고리즘

목록 보기
87/189

- Problem

1706. Where Will the Ball Fall


- 내 풀이

class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        def dfs(y, x):
            if y == M:
                return x

            if x < 0 or x >= N or grid[y][x] == 0:
                return -1
            
            if grid[y][x] == 1:
                return dfs(y+1, x+1)
            
            elif grid[y][x] == -1:
                return dfs(y+1, x-1)
        
        M, N = len(grid), len(grid[0])
        answer = []

        for i in range(M):
            if grid[i][0] == -1:
                grid[i][0] = 0
            
            if grid[i][N-1] == 1:
                grid[i][N-1] = 0

            for j in range(1, N):
                if grid[i][j-1] == 1 and grid[i][j] == -1:
                    grid[i][j-1] = 0
                    grid[i][j] = 0

        for i in range(N):
            x = dfs(0, i)
            if x == -1:
                answer.append(-1)
            else:
                answer.append(x)
        
        return answer

- 결과

- Refactoring Code

class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        def dfs(y, x):
            if y == M:
                return x

            if (x == 0 and grid[y][0] == -1) or (x == N-1 and grid[y][N-1] == 1):
                return -1
            
            if (grid[y][x] == 1 and grid[y][x+1] == -1) or (grid[y][x] == -1 and grid[y][x-1] == 1):
                return -1
     
            return dfs(y+1, x + grid[y][x])

        M, N = len(grid), len(grid[0])

        return list(dfs(0, i) for i in range(N))
profile
Pay it forward.

0개의 댓글