짱이 될거야
백준 2583: 영역 구하기 Python (DFS, BFS) 본문
https://www.acmicpc.net/problem/2583
2583번: 영역 구하기
첫째 줄에 M과 N, 그리고 K가 빈칸을 사이에 두고 차례로 주어진다. M, N, K는 모두 100 이하의 자연수이다. 둘째 줄부터 K개의 줄에는 한 줄에 하나씩 직사각형의 왼쪽 아래 꼭짓점의 x, y좌표값과 오
www.acmicpc.net
1. BFS
from collections import deque
import sys
input = sys.stdin.readline
def bfs(si, sj):
# 초기값
q = deque()
q.append((si, sj))
arr[si][sj] = 1
count = 1
# 반복 조건
while q:
ci, cj = q.popleft()
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = ci+di, cj+dj
if 0 <= ni < M and 0 <= nj < N and not arr[ni][nj]:
count += 1
arr[ni][nj] = 1
q.append((ni, nj))
return count
M, N, K = map(int, input().split()) # M: 행, N: 열, K: 직사각형 수
arr = [[0] * N for _ in range(M)] # arr: 전체 영역
for _ in range(K):
# a, b: 왼쪽 아래 꼭짓점
# c, d: 오른쪽 위 꼭짓점
a, b, c, d = map(int, input().split())
for i in range(M-d, M-b):
for j in range(a, c):
arr[i][j] = 1
result = []
for i in range(M):
for j in range(N):
if not arr[i][j]:
result.append(bfs(i, j))
result.sort()
print(len(result))
print(*result)
2. DFS
dfs로 풀 경우 런타임에러(Recursion Error)가 발생한다.
따라서 sys.setrecursionlimit()을 줘서 해결했다.
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10000)
def dfs(si, sj):
global count
arr[si][sj] = 1
count += 1
for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
ni, nj = si + di, sj + dj
if 0 <= ni < M and 0 <= nj < N and not arr[ni][nj]:
dfs(ni, nj)
M, N, K = map(int, input().split()) # M: 행, N: 열, K: 직사각형 수
arr = [[0] * N for _ in range(M)] # arr: 전체 영역
for _ in range(K):
# a, b: 왼쪽 아래 꼭짓점 / c, d: 오른쪽 위 꼭짓점
a, b, c, d = map(int, input().split())
for i in range(M-d, M-b):
for j in range(a, c):
arr[i][j] = 1
result = []
for i in range(M):
for j in range(N):
if not arr[i][j]:
count = 0
dfs(i, j)
result.append(count)
result.sort()
print(len(result))
print(*result)
'알고리즘' 카테고리의 다른 글
백준 10867: 중복 빼고 정렬하기 Python (0) | 2022.10.14 |
---|---|
백준 10815: 숫자 카드 Python (0) | 2022.10.14 |
백준 2667: 단지번호붙이기 Python (DFS, BFS) (0) | 2022.10.13 |
백준 1926: 그림 Python (BFS) (0) | 2022.10.12 |
백준 2644: 촌수계산 Python (DFS, BFS) (0) | 2022.10.12 |
Comments