๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [Gold4] 2573๋ฒˆ_๋น™์‚ฐ

Dbswnstjd 2023. 1. 4. 02:22

๋ฌธ์ œ

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

 

2573๋ฒˆ: ๋น™์‚ฐ

์ฒซ ์ค„์—๋Š” ์ด์ฐจ์› ๋ฐฐ์—ด์˜ ํ–‰์˜ ๊ฐœ์ˆ˜์™€ ์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๋‘ ์ •์ˆ˜ N๊ณผ M์ด ํ•œ ๊ฐœ์˜ ๋นˆ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. N๊ณผ M์€ 3 ์ด์ƒ 300 ์ดํ•˜์ด๋‹ค. ๊ทธ ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ์ค„๋งˆ๋‹ค ๋ฐฐ์—ด์˜ ๊ฐ ํ–‰์„

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 2573๋ฒˆ ๋ฌธ์ œ - ๋น™์‚ฐ
from collections import deque
dx, dy = [0,0,-1,1], [1,-1,0,0]
n, m = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]

def bfs(x, y):
    q = deque()
    q.append((x, y))
    while q:
        x, y = q.popleft()
        visited[x][y] = 1
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m:
                if graph[nx][ny] > 0 and not visited[nx][ny]:
                    visited[nx][ny] = 1
                    q.append((nx, ny))
                elif graph[nx][ny] == 0:
                    count[x][y] += 1
    return 1

year = 0
while True:
    visited = [[0]*m for _ in range(n)]
    count = [[0]*m for _ in range(n)]
    res = 0
    for i in range(n):
        for j in range(m):
            if graph[i][j] > 0 and not visited[i][j]:
                res += bfs(i,j)
               
    # ๋น™์‚ฐ ๊นŽ๊ธฐ
    for i in range(n):
        for j in range(m):
            if graph[i][j] > count[i][j]:
                graph[i][j] -= count[i][j]
            else:
                graph[i][j] = 0

    if res >= 2:
        break
    if res == 0:
        year = 0
        break
    year += 1

print(year)

Python3 ์œผ๋กœ ์ œ์ถœํ•˜๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•˜์—ฌ pypy3๋กœ ์ œ์ถœํ•˜์˜€๋‹ค.

๋ฌธ์ œ์—์„œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€ ๋น™์‚ฐ์„ ๋ฐ”๋กœ ๊นŽ์ง€ ์•Š๋Š” ๊ฒƒ์ด๋‹ค.