DevYoon

[๋ฐฑ์ค€] 16234. ์ธ๊ตฌ ์ด๋™ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 16234. ์ธ๊ตฌ ์ด๋™ (Python)

gimewn 2022. 6. 17. 02:24

link ๐Ÿ”— https://www.acmicpc.net/problem/16234 

 

16234๋ฒˆ: ์ธ๊ตฌ ์ด๋™

N×Nํฌ๊ธฐ์˜ ๋•…์ด ์žˆ๊ณ , ๋•…์€ 1×1๊ฐœ์˜ ์นธ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๋‹ค. ๊ฐ๊ฐ์˜ ๋•…์—๋Š” ๋‚˜๋ผ๊ฐ€ ํ•˜๋‚˜์”ฉ ์กด์žฌํ•˜๋ฉฐ, rํ–‰ c์—ด์— ์žˆ๋Š” ๋‚˜๋ผ์—๋Š” A[r][c]๋ช…์ด ์‚ด๊ณ  ์žˆ๋‹ค. ์ธ์ ‘ํ•œ ๋‚˜๋ผ ์‚ฌ์ด์—๋Š” ๊ตญ๊ฒฝ์„ ์ด ์กด์žฌํ•œ๋‹ค. ๋ชจ

www.acmicpc.net

 

โœ๏ธ ๊ตญ๊ฒฝ์„ ์„œ๋กœ ๊ณต์œ ํ•˜๋Š” ๊ตญ๊ฐ€๋ฅผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•ด์•ผ ํ• ์ง€ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ๋ฆฌ์ŠคํŠธ์— ๋”ฐ๋กœ ๋‹ด์•„์ฃผ์—ˆ๋‹ค (deque์—์„œ๋Š” pop์„ ํ•˜๋‹ˆ๊นŒ)

โœ๏ธ union(๊ตญ๊ฒฝ ๊ณต์œ  ๊ตญ๊ฐ€ ๋‹ด์•„์ฃผ๋Š” ๊ณณ)์„ ์ฒ˜์Œ์—” set์œผ๋กœ ํ–ˆ๋Š”๋ฐ, 80% ์ฏค์—์„œ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ list๋กœ ๋ฐ”๊ฟ”์ฃผ์—ˆ๋‹ค.

โœ๏ธ ๋”ด์—๋Š” ์ค‘๋ณต ๋ฐฉ์ง€ํ•˜๊ฒ ๋‹ค๊ณ  set์„ ์“ด ๊ฑฐ์˜€๋Š”๋ฐ, ์ƒ๊ฐํ•ด๋ณด๋‹ˆ set์„ ์“ฐ์ง€ ์•Š์•„๋„ ์ค‘๋ณต๊ฐ’์ด ๋“ค์–ด๊ฐˆ ์ผ์ด ์—†์—ˆ๋‹ค.

 

from collections import deque

def BFS(y, x):
    q = deque()
    q.append((y, x))
    union = set()
    union.add((y, x))
    while q:
        ny, nx = q.popleft()
        dir = [(-1, 0), (1, 0), (0, 1), (0, -1)]
        for i, j in dir:
            dy, dx = ny+i, nx+j
            if 0 <= dy < N and 0 <= dx < N and visit[dy][dx] != 1:
                if L <= abs(board[ny][nx] - board[dy][dx]) <= R: # ์ธ๊ตฌ์ˆ˜ ์ฐจ์ด๊ฐ€ ์กฐ๊ฑด์— ๋งž์œผ๋ฉด
                    visit[dy][dx] = 1 # ๋ฐฉ๋ฌธ ์ฒดํฌ
                    q.append((dy, dx)) # q์— ๋‹ด์•„์ฃผ๊ธฐ
                    if (dy, dx) not in union:
                        union.add((dy, dx)) # union set์— ๋‹ด์•„์ฃผ๊ธฐ (๊ตญ๊ฒฝ ๊ณต์œ )
    return union

N, L, R = map(int, input().split())

board = [list(map(int, input().split())) for _ in range(N)]
ans = 0

while True:
    visit = [[0]*N for _ in range(N)]
    flag = False
    for y in range(N):
        for x in range(N):
            if visit[y][x] != 1:
                visit[y][x] = 1
                nation = BFS(y, x) # ํ•œ ๋ฒˆ๋„ ๋“ค๋ฆฐ ์  ์—†์œผ๋ฉด BFS ๋Œ๋ฆฌ๊ธฐ
                if len(nation) > 1: # ๊ตญ๊ฒฝ์„  ์—ด์—ˆ๋‹ค๋Š” ๋œป (1์ด๋ฉด ๊ตญ๊ฐ€ 1๊ฐœ์ด๋ฏ€๋กœ ์—ฐ์‚ฐํ•  ํ•„์š” X)
                    flag = True # flag ๋ฐ”๊พธ๊ธฐ
                    res = 0
                    for i, j in nation: # ๊ตญ๊ฒฝ์„  ๊ณต์œ ํ•˜๊ณ  ์žˆ๋Š” ๊ตญ๊ฐ€๋“ค ์ธ๊ตฌ ์ˆ˜ ๋‹ค ๋”ํ•˜๊ณ 
                        res += board[i][j]
                    res //= len(nation) # ๊ณต์œ ํ•˜๊ณ  ์žˆ๋Š” ๊ตญ๊ฐ€ ์ˆ˜๋กœ ๋‚˜๋ˆ„๊ธฐ
                    for i, j in nation:
                        board[i][j] = res # ์ธ๊ตฌ์ˆ˜ ์žฌ๋ถ„๋ฐฐ
    if flag == False: # ๊ตญ๊ฒฝ์„  ์—ฐ ์  ํ•œ ๋ฒˆ๋„ ์—†์œผ๋ฉด
        break # ๋ธŒ๋ ˆ์ดํฌ

    ans += 1 # +1์ผ

print(ans)