[백준1926] - 그림(Python)

최제원·2024년 8월 1일

algorithm

목록 보기
11/12
post-thumbnail

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

문제 이해

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

문제 포인트

기본 탐색을 진행하며 width와 개수를 구해주면 된다

제출 코드

import sys
from collections import deque

n,m = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)]

number_of_painting = 0
number_of_width = 0

q = deque()

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

def bfs(y, x):
    cnt = 1
    graph[y][x] = 0
    q.append((y, x))
    while q:
        cur_y, cur_x = q.popleft()

        for i in range(4):
            next_y = cur_y + dy[i]
            next_x = cur_x + dx[i]

            if 0 <= next_y < n and 0 <= next_x < m:
                if graph[next_y][next_x]:
                    cnt += 1
                    graph[next_y][next_x] = 0
                    q.append((next_y, next_x))
    return cnt

for y in range(n):
    for x in range(m):
        if graph[y][x] == 1:
            count = bfs(y, x)
            number_of_painting += 1
            if count > number_of_width:
                number_of_width = count

print(number_of_painting)
print(number_of_width)
profile
Why & How

0개의 댓글