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

๐ŸŸฉ [๋ฐฑ์ค€] [Python] 16234๋ฒˆ_์ธ๊ตฌ ์ด๋™

Dbswnstjd 2022. 12. 16. 01:44

๋ฌธ์ œ

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

 

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

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

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 16234๋ฒˆ ๋ฌธ์ œ - ์ธ๊ตฌ ์ด๋™
from collections import deque
dx, dy = [0,0,-1,1], [1,-1,0,0]
n, l, r = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(n)]
answer = 0

def bfs(x, y):
    q = deque()
    q.append((x, y))
    union_country = []
    union_country.append((x,y))
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
                if l <= abs(graph[x][y] - graph[nx][ny]) <= r:
                    visited[nx][ny] = True
                    q.append((nx,ny))
                    union_country.append((nx, ny))
    return union_country
    
while True:
    visited = [[False]*n for _ in range(n)]
    move = False
    for i in range(n):
        for j in range(n):
            if not visited[i][j]:
                visited[i][j] = True
                union_country = bfs(i, j)
                if 1 < len(union_country):
                    move = True
                    population = sum([graph[x][y] for x, y in union_country]) // len(union_country)
                    for x, y in union_country:
                        graph[x][y] = population
    
    if not move:
        break
    else:
        answer += 1

print(answer)

๋ณด๊ธฐ์—” ์‰ฌ์šด ๋ฌธ์ œ์˜€์ง€๋งŒ ์•„์ด๋””์–ด๊ฐ€ ์ƒ๊ฐ๋‚˜์ง€ ์•Š์•„ ๋งค์šฐ ํ—ค๋ฉ”๋‹ค๊ฐ€ ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด๋ฅผ ๋ณด๊ณ  ๊ฒจ์šฐ ํ•ด๊ฒฐํ•˜์˜€๋‹ค. 

 

์ถœ์ฒ˜

https://heytech.tistory.com/377