https://www.acmicpc.net/problem/1012
import sys
def dfs(pos_r, pos_c):
stack = [(pos_r, pos_c)]
matrix[pos_r][pos_c] = 0
dr = [0, 1, 0, -1]
dc = [-1, 0, 1, 0]
while stack:
pos = stack.pop()
for k in range(4):
cr = pos[0] + dr[k]
cc = pos[1] + dc[k]
if(0 <= cr < N and 0 <= cc < M and matrix[cr][cc] == 1):
stack.append((cr, cc))
matrix[cr][cc] = 0
T = int(sys.stdin.readline().rstrip())
for _ in range(T):
M, N, K = map(int, sys.stdin.readline().rstrip().split())
matrix = [[0]*M for _ in range(N)]
answer = 0
for _ in range(K):
pos_c, pos_r = map(int, sys.stdin.readline().rstrip().split())
matrix[pos_r][pos_c] = 1
for i in range(N):
for j in range(M):
if(matrix[i][j] == 1):
answer += 1
dfs(i, j)
print(answer)
'PS > Python' 카테고리의 다른 글
[백준] 15649 - N과 M (1) (파이썬, Python) (0) | 2021.03.27 |
---|---|
2020 카카오 인턴십_수식 최대화(파이썬, Python) (0) | 2021.02.14 |
[백준] 7576 - 토마토 (파이썬, Python) (0) | 2020.07.29 |
[백준] 2667 - 단지번호붙이기 (파이썬, Python) (0) | 2020.07.27 |
[백준] 2178 - 미로 탐색 (파이썬, Python) (0) | 2020.07.23 |