리트코드
리트코드 733 Flood Fill
MC류짱
2022. 9. 24. 15:02
https://leetcode.com/problems/flood-fill/
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
문제
- 2차원 배열이 주어지고, 시작점의 좌표와 바꿀 color를 입력받는다.
- 시작점에서 이어지는 같은 숫자들을 바꾸면 된다.
풀이
class Solution(object):
def floodFill(self, image, sr, sc, color):
N = len(image)
M = len(image[0])
visit = [[0]*M for _ in range(N)]
visit_color = image[sr][sc]
def dfs(r, c):
visit[r][c] = 1
image[r][c] = color
for dr, dc in [[0, 1], [1, 0], [0, -1], [-1, 0]]:
nr, nc = r + dr, c + dc
if 0 <= nr < N and 0 <= nc < M:
if visit[nr][nc] == 0 and image[nr][nc] == visit_color:
dfs(nr, nc)
dfs(sr, sc)
return image