https://www.acmicpc.net/submit/1012/90022364
import sys
sys.setrecursionlimit(10**6)
def dfs(x, y, cabbages, visited, m, n):
if (x, y) not in cabbages or (x, y) in visited:
return
visited.add((x, y))
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < m and 0 <= ny < n:
dfs(nx, ny, cabbages, visited, m, n)
t = int(input())
for _ in range(t):
m, n, k = map(int, input().split())
cabbages = set()
for _ in range(k):
x, y = map(int, input().split())
cabbages.add((x, y))
visited = set()
network = 0
for x, y in cabbages:
if (x, y) not in visited:
dfs(x, y, cabbages, visited, m, n)
network += 1
print(network)