문제 소개
문제
재난방재청에서는 많은 비가 내리는 장마철에 대비해서 다음과 같은 일을 계획하고 있다. 먼저 어떤 지역의 높이 정보를 파악한다. 그 다음에 그 지역에 많은 비가 내렸을 때 물에 잠기지 않는 안전한 영역이 최대로 몇 개가 만들어 지는 지를 조사하려고 한다. 이때, 문제를 간단하게 하기 위하여, 장마철에 내리는 비의 양에 따라 일정한 높이 이하의 모든 지점은 물에 잠긴다고 가정한다.
어떤 지역의 높이 정보는 행과 열의 크기가 각각 N인 2차원 배열 형태로 주어지며 배열의 각 원소는 해당 지점의 높이를 표시하는 자연수이다. 예를 들어, 다음은 N=5인 지역의 높이 정보이다.
사용한 알고리즘
더보기
BFS or DFS
Code
- BFS Code
# Python code
#############################################################################
#
#############################################################################
import sys
import collections
import copy
sys.stdin = open("input.txt", "r")
N = int(input())
graph = []
for i in range(N):
lst = list(map(int,input().split()))
graph.append(lst)
dx = [-1,1,0,0]
dy = [0,0,1,-1]
Q = collections.deque([])
## BFS 탐색
def BFS(x,y,h):
global region
if graph_[x][y]>h:
region = region +1
else:
return
Q.append([x,y])
while Q:
Q_inx = Q.popleft()
for k in range(4):
nx = Q_inx[0]+dx[k]
ny = Q_inx[1]+dy[k]
if 0<=nx<N and 0<=ny<N and graph_[nx][ny]>h:
graph_[nx][ny]=0
Q.append([nx,ny])
h=0
max_region=0
while h<101 :
graph_ = copy.deepcopy(graph)
region = 0
for xi in range(N):
for yi in range(N):
BFS(xi, yi, h)
max_region = max(region,max_region)
h+=1
print(max_region)
- DFS Code
import sys import copy sys.setrecursionlimit(15000) #sys.stdin = open("input.txt", "r") N = int(input()) graph = [] for i in range(N): lst = list(map(int,input().split())) graph.append(lst) dx = [-1,1,0,0] dy = [0,0,1,-1] def DFS(x,y,h): if graph_[x][y]<=h: return graph_[x][y] = 0 for k in range(4): nx = x + dx[k] ny = y + dy[k] if 0 <= nx < N and 0 <= ny < N and graph_[nx][ny] > h: DFS(nx,ny,h) h=0 max_region=0 while h<101 : graph_ = copy.deepcopy(graph) region = 0 for xi in range(N): for yi in range(N): if graph_[xi][yi]>h: DFS(xi, yi, h) region += 1 max_region = max(region,max_region) h+=1 print(max_region)
※ end
반응형
'알고리즘 > 알고리즘 문제' 카테고리의 다른 글
[백준-4963] 섬의 개수 - Python (0) | 2021.12.08 |
---|---|
[백준-9205] 맥주 마시면서 걸어가기 - Python (0) | 2021.12.08 |
[백준-2644] 촌수계산 - Python (0) | 2021.12.08 |
[백준-1260] DFS와 BFS - Python (0) | 2021.12.08 |
[백준-11724] 연결 요소의 개수 - Python (0) | 2021.12.07 |