- Leetcode 733: flood fill - bfs
- Level Easy
- Link
My Approach
Classic bfs problem with replacing existing values into the new value
- Locate the starting number and search through up, down, left, right index.
- Check if the new element is within the rlength and clength
- Check if the new position is not visited
- Check if the new element is equal to the startnum
- If the new element is equal to the startnum
- Append to q and visited
- Replace the new element with startnum
class Solution:
def check(self, r, c, rlimit, climit):
return 0 <= r < rlimit and 0 <= c < climit
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
# locate starting number
startnum = image[sr][sc]
image[sr][sc] = newColor
q = []
visited = []
q.append((sr, sc))
visited.append((sr, sc))
dr, dc = [-1, 1, 0, 0], [0, 0, -1, 1]
while q:
qr, qc = q.pop()
# set new direction
for dir in range(4):
nr = qr + dr[dir]
nc = qc + dc[dir]
# check for index validity
if (nr, nc) not in visited and self.check(nr, nc, len(image), len(image[0])):
# if the new element is equal to startnum
if image[nr][nc] == startnum:
# append to visited and q
visited.append((nr, nc))
q.append((nr, nc))
# change new element to newcolor
image[nr][nc] = newColor
return (image)
'개발공부 > algorithm' 카테고리의 다른 글
[Leetcode][python] 1161: Maximum Level of sum of a binary tree - BFS (0) | 2021.04.27 |
---|---|
[Leetcode][python] 257: binary tree paths - DFS (0) | 2021.04.27 |
[Leetcode][python] 690 - Employee importance - DFS (0) | 2021.04.25 |
[백준][python] 4889 안정적인 문자열 - Greedy (0) | 2021.04.25 |
[백준][python] 1946 신입사원 - Greedy (0) | 2021.04.21 |