본문 바로가기
Algorithm(CodeTree, Python)/DFS

[코드트리] 안전 지대 Python

by kurooru 2023. 2. 27.
# n, m 입력
n, m = map(int, input().split())
# towns
towns = [
    list(map(int, input().split()))
    for _ in range(n)
]

# in_range(x, y)
def in_range(x, y):
    return 0 <= x < n and 0 <= y < m

# is_connected(x, y)
def is_connected(x, y):
    # 범위 내에 있고, 방문한 적 없으며, 현재 높이보다 높으면 가능
    return in_range(x, y) and not visited[x][y] and towns[x][y] > h

# dfs(x, y)
def dfs(x, y):
    # dxs, dys
    dxs, dys = [-1, 1, 0, 0], [0, 0, -1, 1]
    for dx, dy in zip(dxs, dys):
        nx, ny = x + dx, y + dy
        # 이어져 있으면,
        if is_connected(nx, ny):
            # 방문 처리 후
            visited[nx][ny] = True
            # dfs
            dfs(nx, ny)

# 설계
import sys
sys.setrecursionlimit(15000)

# max_height
max_height = 0
for i in range(n):
    for j in range(m):
        max_height = max(max_height, towns[i][j])

# max_safe_area
max_safe_area = -1

# 수면을 올리며 시뮬레이션 진행
for h in range(1, max_height):
    
    # visited
    visited = [
        [0] * m
        for _ in range(n)
    ]

    # curr_safe_area 
    curr_safe_area = 0

    # 마을을 돌며
    for i in range(n):
        for j in range(m):
            # 방문하지 않고, 잠기지 않은 곳을 발견하면
            if not visited[i][j] and towns[i][j] > h:
                # curr_safe_area 올려주고
                curr_safe_area += 1
                # 방문처리 후
                visited[i][j] = True
                # dfs
                dfs(i, j)
    
    # curr_safe_area가 max_safe_area보다 크면
    if curr_safe_area > max_safe_area:
        # k, max_safe_area
        k, max_safe_area = h, curr_safe_area

try:
    print(k, max_safe_area)
except:
    print(1,0)