Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

짱이 될거야

백준 2583: 영역 구하기 Python (DFS, BFS) 본문

알고리즘

백준 2583: 영역 구하기 Python (DFS, BFS)

짱이 되었어 2022. 10. 13. 13:55

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)
Comments