티스토리 뷰

728x90

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

 

1926번: 그림

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

www.acmicpc.net

전형적인 bfs문제입니다.

bfs 시행 횟수를 res 리스트에 저장하여 최댓값을 출력합니다.

res에 결괏값이 없을 시 0을 출력해줍니다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from collections import deque
 
 
def bfs(x, y):
    cnt = 1
    dq = deque()
    dq.append([x, y])
    visit[x][y] = True
    while dq:
        x, y = dq.popleft()
        for dx, dy in direction:
            nx, ny = x + dx, y + dy
            if 0 <= nx < N and 0 <= ny < M and paint[nx][ny] == 1 and not visit[nx][ny]:
                dq.append([nx, ny])
                visit[nx][ny] = True
                cnt += 1
    res.append(cnt)
 
 
N, M = map(int, input().split())
paint, res = [], []
direction = [(01), (10), (0-1), (-10)]
visit = [[False for _ in range(M)] for _ in range(N)]
for i in range(N):
    paint.append(list(map(int, input().split())))
for i in range(N):
    for j in range(M):
        if paint[i][j] == 1 and not visit[i][j]:
            bfs(i, j)
if res:
    print(len(res))
    print(max(res))
else:
    print(0)
    print(0)
cs

 

댓글