짱이 될거야
백준 1012: 유기농 배추 Python (BFS) 본문
https://www.acmicpc.net/problem/1012
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)
'알고리즘' 카테고리의 다른 글
Unity Text Color, Size Script에서 수정하기 (0) | 2022.11.02 |
---|---|
백준 10819: 차이를 최대로 Python (0) | 2022.11.01 |
프로그래머스 SQL: 상품 별 오프라인 매출 구하기 [Oracle] (0) | 2022.10.28 |
프로그래머스 SQL: 년, 월, 성별 별 상품 구매 회원 수 구하기 [Oracle] (0) | 2022.10.28 |
프로그래머스 SQL: 가격대 별 상품 개수 구하기 [Oracle] (0) | 2022.10.28 |
Comments