티스토리 뷰

728x90

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

 

2667번: 단지번호붙이기

<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. 여

www.acmicpc.net

 

 

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
36
37
from collections import deque
 
 
def bfs(x, y):
    dq = deque()
    dq.append([x, y])
    cnt = 0
    while dq:
        x, y = dq.popleft()
        for dx, dy in direction:
            nx, ny = x + dx, y + dy
            if 0 <= nx < N and 0 <= ny < N and arr[nx][ny] == 1 and not visit[nx][ny]:
                visit[nx][ny] = True
                cnt += 1
                dq.append([nx, ny])
    if cnt == 0:
        cnt = 1
    return cnt
 
 
= int(input())
arr = []
visit = [[False for _ in range(N + 1)] for _ in range(N + 1)]
direction = [(01), (10), (0-1), (-10)]
res = []
for _ in range(N):
    lst = list(map(int, input().rstrip()))
    arr.append(lst)
for i in range(N):
    for j in range(N):
        if arr[i][j] == 1 and not visit[i][j]:
            area = bfs(i, j)
            res.append(area)
res.sort()
print(len(res))
for i in res:
    print(i)
cs

 

댓글