Algorithm/noj.am
[Python] 백준 1012번 - 유기농 배추
SweetDev
2021. 1. 26. 06:30
# 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