Algorithm/BFS

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

킹우현 2024. 1. 6. 14:39

 

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

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

www.acmicpc.net

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

t = int(input().rstrip())
    
dx = [-1,1,0,0]
dy = [0,0,-1,1]

for _ in range(t):

    h,w = map(int,input().split())

    answer = 0

    area = [list(input().rstrip()) for _ in range(h)]
    visited = [[False]*w for _ in range(h)]

    def bfs(x,y):

        if visited[x][y] or area[x][y] == ".":
            return False
    
        queue = deque([(x,y)])

        visited[x][y] = True

        while queue:
            temp_x, temp_y = queue.popleft()
            
            for i in range(4):
                nx = temp_x + dx[i]
                ny = temp_y + dy[i]
                
                if 0 <= nx < h and 0 <= ny < w and not visited[nx][ny] and area[nx][ny] == "#":
                    visited[nx][ny] = True
                    queue.append((nx,ny))

        return True
    
    for i in range(h):
        for j in range(w):
            if bfs(i,j):
                answer += 1
    
    print(answer)

 

이번 문제는 DFS/BFS 알고리즘을 활용하여 양(#)무리의 개수를 구하는 문제이다.

 

2차원 배열을 하나씩 순회하면서 탐색해본 결과, 양무리인 경우에 count를 +1 해주는 방식으로 풀 수 있는 간단한 문제이다. 물론 DFS 알고리즘을 사용해도 상관없지만, 본인은 BFS 알고리즘를 사용하여 풀었다.

 

그래프 탐색 알고리즘을 복습할 수 있었던 간단한 문제였다 :)

'Algorithm > BFS' 카테고리의 다른 글

[백준 2636번] 치즈  (0) 2024.06.04
[백준 4485번] 녹색 옷 입은 애가 젤다지?  (0) 2024.04.22
[백준 5427번] 불  (0) 2023.12.29
[SWEA - D4] 보급로  (0) 2023.11.19
[프로그래머스 PCCP 모의고사 2-2번] 시추관  (0) 2023.11.18