https://www.acmicpc.net/problem/1012
1012번: 유기농 배추
차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에
www.acmicpc.net
from collections import deque
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(1, T+1):
M, N, K = map(int,input().split()) # 가로길이 세로길이
arr = [[0] * M for _ in range(N)]
di = [0,0,1,-1]
dj = [1,-1,0,0]
visited = [[0] * M for _ in range(N)]
ans = 0
for _ in range(K):
a, b = map(int,input().split())
arr[b][a] = 1
def bfs(i,j):
global ans
q = deque([(i,j)])
visited[i][j] = 1
while q:
i, j = q.popleft()
for w in range(4):
ni, nj = i+di[w], j+dj[w]
if 0<=ni<N and 0<=nj<M and visited[ni][nj] == 0:
if arr[ni][nj] == 1:
q.append((ni,nj))
visited[ni][nj] = 1
ans += 1
for k in range(N):
for h in range(M):
if arr[k][h] == 1 and visited[k][h] == 0:
bfs(k,h)
print(ans)
❗주의
arr[b][a] 순서 & 마지막 for문에 visited했는지 검사 필수
그리고 ans를 bfs 안에서 더해주는거랑 밖에서 더해주는거랑 비교해봤는데 안에서 해주는게 조금 더 빠름
'백준' 카테고리의 다른 글
백준 27737. 버섯 농장 (0) | 2024.03.05 |
---|---|
백준 7562. 나이트의 이동 (0) | 2024.03.03 |
백준 1926. 그림 (0) | 2024.03.02 |
백준 27527. 배너 걸기 (0) | 2024.03.01 |
백준 28353. 고양이 카페 (0) | 2024.02.28 |