백준-1012

Seogyu Gim·2020년 12월 1일
0

코딩테스트

목록 보기
8/47
from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def bfs(y, x, visited):

    q = deque()
    q.append((y, x))
    visited[y][x] = True

    while q:
        x, y = q.popleft()

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or ny < 0 or nx >= N or ny >= M:
                continue
            if mat[nx][ny] == 1 and visited[nx][ny] == False:
                visited[nx][ny] = True
                q.append((nx, ny))


T = int(input())

for _ in range(T):
    M, N, K = map(int, input().split())
    mat = [[0] * M for _ in range(N)]
    visited = [[False] * M for _ in range(N)]
    cnt = 0
    for i in range(K):
        col, row = map(int, input().split())
        mat[row][col] = 1
    for y in range(N):
        for x in range(M):
            if mat[y][x] == 1 and visited[y][x] == False:
                bfs(y, x, visited)
                cnt += 1
    print(cnt)
profile
의미 있는 일을 하고싶은 개발자

0개의 댓글