-
[백준] 7576. 토마토 (DFS)코테 준비/DFS, BFS 2023. 1. 31. 03:13
from collections import deque dx=[-1,1,0,0] dy=[0,0,-1,1] def dfs(graph): queue=deque() for i in range(n): for j in range(m): if graph[i][j]==1: #그래프를 모두 탐색하여 1인 좌표들을 모두 queue에 넣는다 queue.append((i,j)) while queue: x,y=queue.popleft() for i in range(4): nx=x+dx[i] ny=y+dy[i] if nx<0 or ny<0 or nx>=n or ny>=m: continue if graph[nx][ny]==0: #주변 좌표가 0이면 graph[nx][ny]=graph[x][y]+1 #이전 좌표에+1 queue.append((nx,ny)) m,n=map(int,input().split()) graph=[[0]*m for _ in range(n)] count=0 count2=0 M=0 for i in range(n): graph[i]=list(map(int,input().split())) count+=graph[i].count(0) if count==0: # graph에 0이 한개도 없을 때 즉, 모두 익은 상태면 print(0) # 0 출력 else: #애초에 모두 익은 상태가 아니라면 dfs(graph) #dfs실행 for j in range(n): count2+=graph[j].count(0) M=max(M,max(graph[j])) #graph에서 가장 큰 숫자 찾기 if count2!=0: # dfs를 실행했는데도 안익은 토마토가 남아있다면 print(-1) # -1출력 else: print(M-1) #가장큰 숫자-1 출력
'코테 준비 > DFS, BFS' 카테고리의 다른 글
[백준] 11403. 경로찾기 (bfs) (1) 2023.02.02 [백준] 1697. 숨바꼭질 (다시 풀어보기) (0) 2023.02.02 [백준] 1012. 유기농 배추 (2178. 미로탐색과 유사) (0) 2023.01.20 [백준] 2178. 미로탐색 (BFS) (0) 2023.01.12 [백준] 11724. 연결요소의 개수 (bfs 무방향 그래프) (0) 2023.01.11