티스토리 뷰

# 1012번 유기농배추
import sys


def bfs(row, col):
    queue.insert(0, [row, col])
    while queue:
        current = queue.pop()
        newRow = current[0]
        newCol = current[1]
        # 이웃 찾기
        for a in [-1, 1]:
            if 0 <= (newRow - a) < N:
                if data[newRow - a][newCol] == 1 and [newRow - a, newCol] not in queue:
                    queue.insert(0, [newRow - a, newCol])
        for b in [-1, 1]:
            if 0 <= (newCol - b) < M:
                if data[newRow][newCol - b] == 1 and [newRow, newCol - b] not in queue:
                    queue.insert(0, [newRow, newCol - b])
        data[newRow][newCol] = -1
        groupList[-1] += 1


T = int(sys.stdin.readline())
for _ in range(T):
    M, N, K = map(int, sys.stdin.readline().split())

    # data 만들고 0으로 채우기
    data = []
    data = [[0 for _ in range(M)] for _ in range(N)]
    for k in range(K):
        X, Y = map(int, sys.stdin.readline().split())
        data[Y][X] = 1
    # print(data)
    queue = []
    groupList = []

    for i in range(N):
        for j in range(M):
            if data[i][j] == 1:
                groupList.append(0)
                bfs(i, j)
    print(len(groupList))
    # groupList.sort()
    # print(*groupList, sep='\n')

 

build in pypy

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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 29 30 31
글 보관함