[백준 2573번] 빙산

박형진·2023년 1월 31일
0

https://www.acmicpc.net/problem/2573


1. 코드(pypy3)

import sys

sys.setrecursionlimit(10000)
def dfs(x, y):
    if not (0 <= x < n and 0 <= y < m):
        return

    if visited[x][y]:
        visited[x][y] = False
        dfs(x-1, y)
        dfs(x+1, y)
        dfs(x, y-1)
        dfs(x, y+1)

n, m = map(int, sys.stdin.readline().rstrip().split())
graph = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(n)]
visited = [[False] * m for _ in range(n)]
year = 1

while True:
    ice = set()
    cnt = 0
    flag = False
    remove_pos = []
    for i in range(1, n-1):
        for j in range(1, m-1):
            if graph[i][j] != 0:
                flag = True
                visited[i][j] = True
                ice.add((i, j))
                remove = 0
                if graph[i-1][j] == 0:
                    remove += 1
                if graph[i+1][j] == 0:
                    remove += 1
                if graph[i][j-1] == 0:
                    remove += 1
                if graph[i][j+1] == 0:
                    remove += 1

                if remove:
                    remove_pos.append((i, j, remove))
    # 다 녹았으면 탈출
    if not flag:
        print(0)
        break

    for x, y, qty in remove_pos:
        if graph[x][y] - qty <= 0:
            graph[x][y] = 0
            visited[x][y] = False
            ice.remove((x, y))
        else:
            graph[x][y] -= qty

    for i in range(1, n-1):
        for j in range(1, m-1):
            if visited[i][j]:
                dfs(i, j)
                cnt += 1
    if cnt >= 2:
        print(year)
        break
    year += 1

    for x, y in ice:
        visited[x][y] = True
profile
안녕하세요!

0개의 댓글