Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

짱이 될거야

백준 1012: 유기농 배추 Python (BFS) 본문

알고리즘

백준 1012: 유기농 배추 Python (BFS)

jeong57 2022. 10. 31. 10:23

https://www.acmicpc.net/problem/1012

 

1012번: 유기농 배추

차세대 영농인 한나는 강원도 고랭지에서 유기농 배추를 재배하기로 하였다. 농약을 쓰지 않고 배추를 재배하려면 배추를 해충으로부터 보호하는 것이 중요하기 때문에, 한나는 해충 방지에 

www.acmicpc.net

 

 

from collections import deque
import sys
input = sys.stdin.readline


def bfs(si, sj):
    q = deque()
    q.append((si, sj))
    visited[si][sj] = 1

    while q:
        si, sj = q.popleft()
        for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            ni, nj = si+di, sj+dj
            if 0 <= ni < N and 0 <= nj < M and not visited[ni][nj] and farm[ni][nj]:
                visited[ni][nj] = 1
                q.append((ni, nj))


T = int(input())
for tc in range(T):
    M, N, K = map(int, input().split())     # M: 가로, N: 세로, K: 배추 개수
    farm = [[0] * M for _ in range(N)]
    for _ in range(K):
        x, y = map(int, input().split())
        farm[y][x] = 1
    cnt = 0
    visited = [[0] * M for _ in range(N)]   # 방문체크
    for i in range(N):
        for j in range(M):
            if not visited[i][j] and farm[i][j]:
                bfs(i, j)
                cnt += 1
    print(cnt)
Comments