반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 연필
- Python
- 코드잇
- 취미
- 다비드상
- 코딩
- leetcode
- PrivateRouter
- IT 자격증
- 테스팅 자격증
- 프로그래밍
- Kriss 재택
- 색연필
- csts
- 프로그래머스
- 클린 코드
- 연필소묘
- 재택근무
- 알고리즘
- clean code
- IT자격증
- 토익 환급
- 미켈란젤로
- 파이썬
- 그림
- 웹개발
- 소묘
- react
- KSTQB
- 코딩테스트
Archives
- Today
- Total
글모음
[Leetcode] 733. Flood Fill [Easy, Python] 본문
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문을 저렇게 리스트를 바로 만들어서 사용할 수 있다는 걸 잘 기억해두자
728x90
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
[Leetcode] 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree [Python, Medium] (0) | 2021.06.18 |
---|---|
[Leetcode] 144. Binary Tree Preorder Traversal [Python, Easy] (0) | 2021.06.12 |
1441. Build an Array With Stack Operations [Easy, Python] (0) | 2021.03.06 |
682. Baseball Game [Easy, Python] (0) | 2021.03.06 |
Leetcode 문제풀이 목록 (0) | 2021.03.06 |
Comments