알고리즘

백준 2667번 : 단지번호붙이기(python)

jenyy 2021. 7. 26. 18:26

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

 

2667번: 단지번호붙이기

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

www.acmicpc.net

 

n = int(input())
data = [list(map(int, input())) for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def dfs(x, y):
    count = 1
    data[x][y] = 0
    q = [(x, y)]
    while q:
        x, y = q.pop()
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < n and 0 <= ny < n and data[nx][ny] == 1:
                q.append((nx,ny))
                data[nx][ny] = 0
                count += 1
    return count


result = 0
number = []
for x in range(n):
    for y in range(n):
        if data[x][y] == 1:
            result += 1
            c = dfs(x, y)
            number.append(c)

number.sort()
print(result)
for num in number:
     print(num)