백준 2573 빙산 Python

Derhon·2023년 11월 30일
0

백준 2573 빙산

29.46m

나의 답

import sys
from collections import deque

n, m = list(map(int, sys.stdin.readline().rstrip().split()))
board = [list(map(int, sys.stdin.readline().rstrip().split())) for _ in range(n)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def bfs(node):
    q = deque([node])
    while q:
        px, py = q.popleft()
        for i in range(4):
            nx, ny = px + dx[i], py + dy[i]
            if (0 <= nx < n) and (0 <= ny < m) and (not visited[nx][ny]) and (board[nx][ny] > 0):
                visited[nx][ny] = True
                q.append((nx, ny))

year = 0
while True:
    visited = [[False] * m for _ in range(n)]
    cnt = 0
    for i in range(n):
        for j in range(m):
            if (not visited[i][j]) and (board[i][j] > 0):
                bfs((i, j))
                cnt += 1
    temp = [arr[:] for arr in board]
    for i in range(n):
        for j in range(m):
            if board[i][j] <= 0: continue
            sea = 0
            for d in range(4):
                nx, ny = i + dx[d], j + dy[d]
                if (0 <= nx < n) and (0 <= ny < m) and (board[nx][ny] <= 0): sea += 1
            temp[i][j] -= sea
    if cnt == 0:
        print(0)
        break
    if cnt >= 2:
        print(year)
        break
    board = temp
    year += 1

시간을 재니까 뭔가 쫓기듯 빠르게 풀었는데
대신 코드가 지저분해진다ㅠㅠ
라고 하고 다른 답을 찾아봤는데 다들 길게 풀었네요 원래 그런문제인가보다

profile
🧑‍🚀 이사했어요 ⮕ https://99uulog.tistory.com/

0개의 댓글