Algorithm/BFS

[백준 1926번] 그림

킹우현 2023. 10. 3. 02:23

 

1926번: 그림

어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로

www.acmicpc.net

from collections import deque

n, m = map(int,input().split())

area = [list(map(int,input().split())) for _ in range(n)]

visited = [[0]*m for _ in range(n)]

count_list = []

dx = [-1,1,0,0]
dy = [0,0,-1,1]

def bfs(x,y):
    if visited[x][y] != 0 or area[x][y] != 1:
        return -1
    
    visited[x][y] = 1
    
    queue = deque([(x,y)])
    total = 1

    while queue:
        cur_x, cur_y = queue.popleft()

        for i in range(4):
            nx = cur_x + dx[i]
            ny = cur_y + dy[i]
            
            if 0 <= nx < n and 0 <= ny < m and area[nx][ny] == 1 and visited[nx][ny] == 0:
                visited[nx][ny] = visited[cur_x][cur_y] + 1
                total += 1
                queue.append((nx,ny))

    return total

for i in range(n):
    for j in range(m):
        count = bfs(i,j)
        if count != -1:
            count_list.append(count)

print(len(count_list))

if len(count_list) == 0:
    print(0)
else:
    print(max(count_list))

이번 문제는 입력값에서 색칠된 부분으로 이어진 그림의 개수와 그림의 넓이의 최댓값을 구하는 문제이다.

 

DFS나 BFS를 사용해서 그림의 모든 부분을 탐색하고, 그림의 넓이를 모두 구한 뒤 개수와 최댓값을 구해주면 된다. 본인은 BFS를 사용해서 풀이했는데, DFS와 BFS를 복습할 수 있었던 문제였다 :)

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

[백준 4179번] 불!  (1) 2023.10.03
[백준 2178번] 미로 탐색  (0) 2023.10.03
[프로그래머스 Lv.3] 단어 변환  (0) 2023.09.29
[SWEA 5102번] 노드의 거리  (1) 2023.09.21
[SWEA 5105번] 미로의 거리  (0) 2023.09.21