This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
from collections import deque | |
dx = [-1, 1, 0, 0] | |
dy = [0, 0, 1, -1] | |
def bfs(n, m, xl, yl): | |
a = deque() | |
a.append((n, m)) | |
visited[n][m] = True | |
while a: | |
x, y = a.popleft() | |
for i in range(4): | |
nx = x + dx[i] | |
ny = y + dy[i] | |
if 0 <= nx < xl and 0 <= ny < yl: | |
if farm[nx][ny] == 1 and not visited[nx][ny]: | |
a.append((nx, ny)) | |
visited[nx][ny] = True | |
testCase = int(input()) | |
for i in range(testCase): | |
count = 0 | |
m, n, k = map(int, sys.stdin.readline().split()) | |
farm = [[0]*m for _ in range(n)] | |
visited = [[False]*m for _ in range(n)] | |
for j in range(k): | |
x, y = map(int, sys.stdin.readline().split()) | |
farm[y][x] = 1 | |
for i in range(n): | |
for j in range(m): | |
if not visited[i][j] and farm[i][j] == 1: | |
bfs(i, j, n, m) | |
count += 1 | |
print(count) | |
'코딩테스트 준비' 카테고리의 다른 글
크루스칼 알고리즘 - 최소 스패닝 트리 (0) | 2021.04.03 |
---|---|
백준 알고스팟 - 우선순위 큐, 너비우선탐색 (0) | 2021.03.21 |
백준 최대 힙, 절댓값 힙 - heapq 사용, 파이썬 (0) | 2021.03.13 |
백준 최대 힙, 절댓값 힙 - heapq 사용, 파이썬 (0) | 2021.03.13 |
파이썬 itertools permutations! (0) | 2021.03.04 |