chyam

[백준] 2468번,python - 안전 영역 본문

백준

[백준] 2468번,python - 안전 영역

chyam_eun 2026. 1. 19. 16:15

 

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

import sys
from collections import deque
input = sys.stdin.readline

n = int(input())
space = [] # 땅 높이
max_len, res = 0, 0
direct = [[0,1],[0,-1],[1,0],[-1,0]] # 방향 설정 

for _ in range(n):
    tmp = list(map(int,input().split()))
    max_len = max(max(tmp),max_len) # 빗물 최대 높이
    space.append(tmp)

def bfs(l, i, j):
    queue = deque([(i,j)]) # 시작 지점 
    visited[i][j] = True
    
    while queue:
        x, y = queue.popleft()
        for dx, dy in direct: # 상하좌우로 탐색 시작 
            nx, ny = x + dx, y + dy
            if 0 <= nx < n and 0 <= ny < n: # 범위 내에서만 
                if space[nx][ny] > l and not visited[nx][ny]: # 기준치보다 높을때만 이동 가능 + 방문하지 않은곳 추가
                    queue.append([nx,ny]) # 갈수있는곳 추가
                    visited[nx][ny] = True # 방문 처리

for l in range(max_len):

    visited = [[False] * n for _ in range(n)]
    cnt = 0
    for i in range(n):
        for j in range(n):
            if not visited[i][j] and space[i][j] > l: # 방문하지 않았고 일정 높이 이상이어야함
                bfs(l,i,j)
                cnt += 1 # 안전 영역 + 1
    res = max(res,cnt) # 최대 영역 저장
print(res)