글모음

[Leetcode] 733. Flood Fill [Easy, Python] 본문

알고리즘/Leetcode

[Leetcode] 733. Flood Fill [Easy, Python]

Nova_61 2021. 6. 15. 13:36
728x90
반응형

 

기준점 상하좌우 탐색해서 같다면 newColor 값으로 바꿔주는 DFS 문제

 

 

 

[ 코드 1. 실패 ]

def floodFill(self, image, sr, sc, newColor):
        limit_x = list(range(len(image)+1))
        limit_y = list(range(len(image[0])))

        l_color = image[sr][sc]

        def dfs(x, y):
            positions = [[x, y-1], [x, y+1], [x-1, y], [x+1, y]]

            if x in limit_x and y in limit_y:
                if image[x][y] == l_color:
                    image[x][y] = newColor
                    for i in range(len(positions)):
                        if positions[i][0] in limit_x and positions[i][1] in limit_y:
                            dfs(positions[i][0], positions[i][1])

        dfs(sr, sc)
        return image
        

이런 문제는 범위가 제일 중요한데, 이 코드로는 x + 1, x -1, y + 1, y -1일 때를 걸러주지 못해서 out of range 오류가 난다.

DFS 문제를 풀때는 꼭 범위를 잘 확인하자.

 

[ 코드 2. 수정 ]

class Solution:
    def floodFill(self, image, sr, sc, newColor):
        def dfs(i, j):
            image[i][j] = newColor
            for x, y in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]:
                if 0 <= x < m and 0 <= y < n and image[x][y] == f_color:
                    dfs(x, y)
        f_color, m, n = image[sr][sc], len(image), len(image[0])
        if f_color != newColor:
            dfs(sr, sc)
        return image
        
        

1번 코드에서 out of range 오류가 나서 범위 체크하는 부분을 넣었다.

for문을 저렇게 리스트를 바로 만들어서 사용할 수 있다는 걸 잘 기억해두자

 

 

 

Flood Fill - 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

 

728x90
반응형
Comments