Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 11. 1. 23:30

https://leetcode.com/problems/where-will-the-ball-fall/

 

Where Will the Ball Fall - 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

딱봐도 DFS/BFS 문제긴 한데..
사선으로 되어 있어서 접근하기가 뭔가 =_=;

class Solution:
    def findBall(self, grid: List[List[int]]) -> List[int]:
        m, n = len(grid), len(grid[0])
        
        def check(r, c):
            if r == m:
                return c
            
            nc = c + grid[r][c]
            
            if nc == n or nc == -1 or grid[r][nc] != grid[r][c]:
                return -1
            else:
                return check(r+1, nc)
        
        res = []
        
        for i in range(n):
            res.append(check(0, i))
        
        return res
반응형