백준 1012 - 유기농 배추 (파이썬)

Updated:

Answer

from sys import stdin, setrecursionlimit
input = stdin.readline
setrecursionlimit(10000)

def dfs(x, y):
    if x < 0 or x >= N or y < 0 or y >= M:
        return

    if matrix[x][y] == 1:
        matrix[x][y] = 0

        for nx, ny in (0, 1), (0, -1), (1, 0), (-1, 0):
            dfs(x + nx, y + ny)

for _ in range(int(input())):
    M, N, K = map(int, input().split())
    matrix = [[0] * M for _ in range(N)]
    count = 0

    for _ in range(K):
        a, b = map(int, input().split())
        matrix[b][a] = 1

    for i in range(N):
        for j in range(M):
            if matrix[i][j] == 1:
                dfs(i, j)
                count += 1

    print(count)

Categories:

Updated: