[백준] 11123번 양 한마리... 양 두마리...

거북이·2023년 7월 21일
0

백준[실버2]

목록 보기
68/81
post-thumbnail

💡문제접근

  • W, H를 잘못 입력받아서 IndexError가 나왔다. 문제 똑바로 읽었으면....

💡코드(메모리 : 34168KB, 시간 : 308ms)

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

def BFS(a, b):
    queue = deque()
    queue.append((a, b))
    while queue:
        y, x = queue.popleft()
        dx = [-1, 0, 1, 0]
        dy = [0, 1, 0, -1]
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= W or ny < 0 or ny >= H:
                continue
            if 0 <= nx < W and 0 <= ny < H and graph[ny][nx] == '#':
                queue.append((ny, nx))
                graph[ny][nx] = '.'

T = int(input())
for _ in range(T):
    H, W = map(int, input().strip().split())
    graph = []
    for _ in range(H):
        graph.append(list(map(str, input().strip())))

    answer = 0
    for i in range(H):
        for j in range(W):
            if graph[i][j] == '#':
                answer += 1
                BFS(i, j)
    print(answer)

💡소요시간 : 18m

0개의 댓글