-
[LeetCode] 773. Flood Fill알고리즘 2022. 5. 26. 23:23
[LeetCode] 773. Flood Fill
DFS 로 풀 수 있는 문제이다.
나의 풀이
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: n = len(image) m = len(image[0]) visited = [[0] * m for _ in range(n)]; dx = [1,-1,0,0] dy = [0,0,1,-1] def dfs(r,c, targetColor, newColor): for _ in range(4): newR = r + dy[_] newC = c + dx[_] if (newR < 0 or newR >= n or newC < 0 or newC >= m or visited[newR][newC] or image[newR][newC] != targetColor): continue; image[newR][newC] = newColor visited[newR][newC] = 1 dfs(newR, newC, targetColor, newColor) targetColor = image[sr][sc] dfs(sr,sc, targetColor, newColor); image[sr][sc] = newColor return image
다른 사람의 더 간단명료한 풀이
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: self.dfs(image, sr, sc, image[sr][sc], newColor) return image def dfs(self, image, m, n, oldValue, newValue): if m < 0 or m > len(image)-1 or n < 0 or n > len(image[0])-1 or image[m][n] == newValue: return if image[m][n] == oldValue: image[m][n] = newValue self.dfs(image, m-1, n, oldValue, newValue) self.dfs(image, m+1, n, oldValue, newValue) self.dfs(image, m, n-1, oldValue, newValue) self.dfs(image, m, n+1, oldValue, newValue) return
'알고리즘' 카테고리의 다른 글
[LeetCode] 1254. Number of Closed Islands (0) 2022.05.29 [LeetCode] 695. Max Area of Island (0) 2022.05.28 [Python] 팰린드롬 알고리즘 (Palindrome Algorithm) 설명 및 예제 (0) 2022.05.14 [python] 파이썬 Counter 함수 사용법 (0) 2022.05.06 파이썬 combinations 사용법 [python, 파이썬] (0) 2022.05.06