일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- Python
- codeup
- 릿코드
- heap
- 니트코드
- 생성형AI
- SQL
- 슬라이딩윈도우
- 파이썬
- 리트코드
- 코드업
- 파이썬알고리즘
- Greedy
- dfs
- Stack
- nlp
- slidingwindow
- stratascratch
- 투포인터
- 파이썬기초100제
- sql코테
- GenerativeAI
- 알고리즘
- array
- gcp
- 자연어처리
- two-pointer
- GenAI
- Python3
- LeetCode
Archives
- Today
- Total
Tech for good
[Leetcode/DFS, BFS, Matrix] 733. Flood Fill 본문
Depth-First Search (DFS)
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
original_color = image[sr][sc]
if original_color == color:
return image # No need to do anything if the target color is the same
rows, cols = len(image), len(image[0])
def dfs(r, c):
if (r < 0 or r >= rows or c < 0 or c >= cols): # 좌표가 2차원 격자를 벗어낫을때
return # 함수를 종료시킨다
if image[r][c] != original_color:
return
image[r][c] = color # Change color
# Visit 4-directionally
dfs(r + 1, c) # 상
dfs(r - 1, c) # 하
dfs(r, c + 1) # 좌
dfs(r, c - 1) # 우
dfs(sr, sc)
return image
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
R, C = len(image), len(image[0])
color = image[sr][sc]
if color == newColor:
return image
def dfs(r, c):
if image[r][c] == color:
image[r][c] = newColor
if r >= 1:
dfs(r-1, c)
if r + 1 < R:
dfs(r + 1, c)
if c >= 1:
dfs(r, c - 1)
if c + 1 < C:
dfs(r, c + 1)
dfs(sr, sc)
return image
Breadth-First Search (BFS)
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
gridRowSize = len(image)
gridColSize = len(image[0])
prevColor = image[sr][sc]
if prevColor == color:
return image
moves = [(1, 0), (-1, 0), (0, 1), (0, -1)] # Key
q = deque()
q.append((sr, sc))
while q:
r, c = q.popleft()
image[r][c] = color
for dr, dc in moves:
nr, nc = r + dr, c + dc
if (0 <= nr < gridRowSize and 0 <= nc < gridColSize and
image[nr][nc] == prevColor):
q.append((nr, nc))
return image