본문 바로가기
Algorithm/baekjoon

[파이썬]baekjoon 11123: 양 한마리... 양 두마리...

by 갈잃자 2022. 12. 14.

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

 

11123번: 양 한마리... 양 두마리...

얼마전에 나는 불면증에 시달렸지... 천장이 뚫어져라 뜬 눈으로 밤을 지새우곤 했었지.  그러던 어느 날 내 친구 광민이에게 나의 불면증에 대해 말했더니 이렇게 말하더군. "양이라도 세봐!"  

www.acmicpc.net


간단한 bfs문제. dfs로도 풀 수 있지만, 영역을 구하는 문제는 bfs가 편한거 같아서 bfs로 풀었다.

 

#가 상하좌우로 밀집해 있다면, 하나의 군집으로 체크!

def bfs(start):
    q = []
    q.append(start)
    arr[y][x] = "."
    directy = [-1, 1, 0, 0]
    directx = [0, 0, -1, 1]
    while q:
        nowy, nowx = q.pop(0)

        for i in range(4):
            dy = directy[i] + nowy
            dx = directx[i] + nowx

            if 0<=dy<H and 0<=dx<W :
                if arr[dy][dx] ==".": continue
                if arr[dy][dx] =="#":
                    q.append((dy,dx))
                    arr[dy][dx] = "."


t = int(input())
for tc in range(t):
    H,W = list(map(int,input().split()))
    arr=[list(input()) for _ in range(H)]
    answer = 0
    for y in range(H):
        for x in range(W):
            if arr[y][x] =="#":
                arr[y][x] = "."
                bfs((y,x))
                answer += 1
    print(answer)

댓글