본문 바로가기
알고리즘/dfs,bfs

[파이썬🐍] 백준 2583 : 영역 구하기

by 코딩개미뚠뚠 2021. 4. 9.
반응형

영어 공부하느라 포스팅이 늦어졌다..ㅎ

음 여기서 주의해야 할 점은 cnt 초기화를 0값이 아닌 1로 해줘야 한다는 점??

기억하자 나의 머리야!!

좀 오래걸렸지만 풀고보니 많이 어렵진 않았다.

from collections import deque
dx = [-1,1,0,0]
dy = [0,0,-1,1]
q = deque()
def bfs(i,j):
    q.append([i,j])
    matrix[i][j] = 1
    cnt = 1
    while q:
        x,y = q.popleft()
        for i in range(4):
            nx = x+dx[i]
            ny = y+dy[i]
            if (0 <= nx < m) and (0 <= ny <n):
                if matrix[nx][ny] == 0:
                    matrix[nx][ny] = 1
                    q.append([nx,ny])
                    cnt += 1
    return cnt



m,n,k = map(int,input().split())
matrix = [[0]*n for _ in range(m)]
for _ in range(k):
    x,y,a,b = map(int,input().split())
    for i in range(y,b):
        for j in range(x,a):
            matrix[i][j] = 1

block_list = []
for i in range(m):
    for j in range(n):
        if matrix[i][j] == 0:
            block = bfs(i,j)
            if block:
                block_list.append(block)

print(len(block_list))
block_list.sort()
for i in range(len(block_list)):
    print(block_list[i],end=' ')

 

반응형

댓글