반응형
프로그래머스 레벨1,2까지는 dfs로 풀만한 문제들이 거의 없다.
요즘 프로그래머스만 풀다보니까 dfs와 bfs를 까먹고 있다는 느낌이 들어서
다시 백준으로 넘어와서 문제를 풀어보려한다.
from collections import deque
m,n = map(int,input().split())
s = []
queue = deque()
dx = [1,-1,0,0]
dy = [0,0,-1,1]
for i in range(n):
s.append(list(map(int,input().split())))
def bfs():
while queue:
a,b = queue.popleft()
for i in range(4):
x = a+dx[i]
y = b+dy[i]
if 0 <= x < n and 0 <= y < m and s[x][y] == 0:
s[x][y] = s[a][b] + 1
queue.append([x,y])
for i in range(n):
for j in range(m):
if s[i][j] == 1:
queue.append([i,j])
bfs()
isTrue = False
result = -2
for i in s:
for j in i:
if j == 0:
isTrue = True
result = max(result,j)
if isTrue == True: #토마토가 하나라도 익지 않은 경우
print(-1)
elif result == -1: #처음부터 토마토가 -1(익음)경우
print(0)
else:
print(result-1)
오랜만에 풀려고 하니까 어렵지 않은 문제임에도 헷갈렸다😓
반응형
'알고리즘 > dfs,bfs' 카테고리의 다른 글
[파이썬🐍] 백준 7562 : 나이트의 이동 (0) | 2021.05.31 |
---|---|
[파이썬🐍] 백준 1012 : 유기농 배추 (0) | 2021.05.30 |
[파이썬🐍] 백준 4963 : 섬의 개수 (0) | 2021.04.12 |
[파이썬🐍] 백준 2644 : 촌수계산 (0) | 2021.04.11 |
[파이썬🐍] 백준 10026 : 적록색약 (0) | 2021.04.10 |
댓글