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

이런 그룹화? 묶음 세기 는 무조건 dfs 로 푸는데, dfs 로 풀고 최적화 를 해도 계속 런타임에러가 떠서 bfs 로 바꿔 풀었다.
import sys
from collections import deque
input = sys.stdin.readline
n = int(input())
graph = []
for _ in range(n):
graph.append(list(map(int, input().split())))
maxnum = max(max(row) for row in graph)
# BFS 함수 정의
def bfs(x, y, height, visited):
queue = deque([(x, y)])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
visited[x][y] = True
while queue:
x, y = queue.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny] and graph[nx][ny] > height:
visited[nx][ny] = True
queue.append((nx, ny))
# 모든 가능한 높이에 대해 안전 영역 계산
answer = []
for height in range(0, maxnum + 1): # 수정: minnum이 아니라 0에서 시작
visited = [[False] * n for _ in range(n)]
count = 0
for i in range(n):
for j in range(n):
if graph[i][j] > height and not visited[i][j]:
bfs(i, j, height, visited)
count += 1
answer.append(count)
print(max(answer))