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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | import sys from collections import deque def find_node(y, x): array = [] dy = [0, 0, –1, 1] dx = [–1, 1, 0, 0] for i in range(4): ny = y + dy[i] nx = x + dx[i] if 0 <= nx < m and 0 <= ny < n: if graph[ny][nx] == 1: array.append((ny, nx)) return array def bfs(start): global num queue = deque([start]) graph[start[0]][start[1]] = 2 num += 1 while queue: v = queue.popleft() arr = find_node(v[0], v[1]) for i in arr: queue.append(i) graph[i[0]][i[1]] = 2 t = int(sys.stdin.readline().strip()) for _ in range(t): m, n, k = map(int, sys.stdin.readline().strip().split()) num = 0 graph = [[0] * m for _ in range(n)] for _ in range(k): a, b = map(int, sys.stdin.readline().strip().split()) graph[b][a] = 1 for i in range(n): for j in range(m): if graph[i][j] == 1: bfs((i, j)) print(num) | cs |