-
[코테]99클럽 코테 스터디 10일차 TIL 백준 2573 빙산코딩테스트 2025. 1. 26. 16:37
https://www.acmicpc.net/problem/2573
이 문제는 그래프 탐색 문제로, 문제에서 설명하는대로 착실하게 구현만 하면 되는?(그게 어렵지만,,)문제라고 할 수 있다.
빙산이 분리가 되는지 탐색하는 것은 bfs를 통해 구현하였고, 1년 후 빙산의 상태는 이중 for문으로 구현하였다.
중요한 점은 방문 그래프가 반복문을 실행할 때마다 초기화 되어야 한다는 것이다.
import sysfrom collections import deque
read = sys.stdin.readline
N, M = map(int, read().split())graph = []for _ in range(N):graph.append(list(map(int, read().split())))
# 상하좌우dx = [-1,1,0,0]dy = [0,0,-1,1]
# 경계 검사 함수def is_valid(x, y):return 0 <= x < N and 0 <= y < M
# 다 녹았는지 검사def is_melt(graph):for i in range(N):for j in range(M):if graph[i][j] != 0:return Falsereturn True
# 1년 후 빙산 상태def after_one_year(graph):new_graph = [row[:] for row in graph] # 기존 그래프 복사for i in range(N):for j in range(M):if graph[i][j] > 0: # 현재 위치가 0이 아닐 때만cnt = sum(1 for k in range(4) if is_valid(i + dx[k], j + dy[k]) and graph[i + dx[k]][j + dy[k]] == 0)new_graph[i][j] -= cntif new_graph[i][j] < 0:new_graph[i][j] = 0return new_graph
def bfs(x,y,visited,graph):queue = deque([(x,y)])visited[x][y] = Truewhile queue:x, y = queue.popleft()for i in range(4):nx = x + dx[i]ny = y + dy[i]if 0 <= nx < N and 0 <= ny < M and graph[nx][ny] != 0 and not visited[nx][ny]:visited[nx][ny] = Truequeue.append((nx,ny))
def result(graph):year_cnt = 0while True:# 녹기 전 빙산 덩어리 수 확인visited = [[False for _ in range(M)] for _ in range(N)]ice_cnt = 0
for i in range(N):for j in range(M):if graph[i][j] != 0 and not visited[i][j]:ice_cnt += 1bfs(i, j, visited, graph)
if ice_cnt >= 2: # 빙산이 분리된 경우return year_cntif is_melt(graph): # 모든 빙산이 녹은 경우return 0
# 1년 경과graph = after_one_year(graph)year_cnt += 1
print(result(graph))'코딩테스트' 카테고리의 다른 글
[코테]백준 1913 달팽이 파이썬 (0) 2025.01.31 [코테]백준 16236 아기상어 파이썬 (0) 2025.01.31 [코테] 백준 14891 톱니바퀴 파이썬 (0) 2025.01.22 [코테]99클럽 코테스터디 8일차 TIL 백준 2667 단지번호붙이기 (0) 2025.01.22 [코테]99클럽 코테스터디 7일차 TIL 백준 1697 숨바꼭질 (0) 2025.01.21