728x90
https://www.acmicpc.net/problem/2573
2573번: 빙산
첫 줄에는 이차원 배열의 행의 개수와 열의 개수를 나타내는 두 정수 N과 M이 한 개의 빈칸을 사이에 두고 주어진다. N과 M은 3 이상 300 이하이다. 그 다음 N개의 줄에는 각 줄마다 배열의 각 행을
www.acmicpc.net
해당 문제는 너비우선탐색 으로 문제를 해결하였습니다. 빙산을 녹이는 함수 ( 너비우선탐색으로 구현 ), 빙산의 그룹의 개수를 체크하는 함수 ( 너비우선탐색으로 구현) 으로 구현하였습니다. 그룹의 개수가 2이상일경우 년도를 출력하고 그룹의 개수가0 인경우는 모두 바다이기때문에 0을 출력합니다.
from collections import deque
N, M = map(int, input().split()) # 세로, 가로
graph = [list(map(int, input().split())) for _ in range(N)]
move = [(0,1), (0,-1), (1,0), (-1,0)]
def oneYearsGo():
value = [[0 for _ in range(M)] for _ in range(N)]
for i in range(N):
for j in range(M):
if graph[i][j] > 0:
for dy,dx in move:
ny = dy + i
nx = dx + j
if N > ny >=0 and M > nx >=0 and graph[ny][nx] == 0: # 주변이 바다라면
value[i][j] += 1 # 녹인다.
for i in range(N):
for j in range(M):
if graph[i][j] > 0:
graph[i][j] = max(0, graph[i][j] - value[i][j])
return 1
def bfs(i,j):
queue = deque()
if graph[i][j] > 0 and not visited[i][j]: # 빙산이라면
queue.append((i,j))
visited[i][j] = True
while queue:
y, x = queue.popleft()
for dy,dx in move:
ny = dy + y
nx = dx + x
if N > ny >=0 and M > nx >=0 and graph[ny][nx] > 0 and not visited[ny][nx]: # 주변이 빙산이라면
visited[ny][nx] = True
queue.append((ny,nx))
return 1
else:
return 0
years = 0
while True:
count = 0
oneYearsGo()
years += 1
visited = [[False for _ in range(M)] for _ in range(N)]
for i in range(N):
for j in range(M):
count += bfs(i,j)
if count >= 2 or count ==0:
if count == 0:
print(0)
else:
print(years)
break
728x90
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 17472번 : 다리 만들기 2 (0) | 2023.07.31 |
---|---|
[백준] 1011번 : Fly me to the Alpha Centauri (0) | 2023.07.30 |
[백준] 4991번 : 로봇 청소기 (0) | 2023.07.30 |
[백준] 1194번 : 달이 차오른다, 가자. (0) | 2023.07.29 |
[백준] 1806번 : 부분합 (0) | 2023.07.26 |