[Python][DFS]단지번호 붙이기

 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
direction = ((-1,0), (1,0), (0,-1), (0,1))

def bfs(y, x, num):
    global n
    check[y][x] = num
    queue = [(y,x)]
    cnt = 1
    while queue:
        curr_y, curr_x = queue.pop(0)
        for d in direction:
            next_y = curr_y + d[0]
            next_x = curr_x + d[1]
            if 0<=next_y<n and 0<=next_x<n:
                if MAP[next_y][next_x] == 1 and check[next_y][next_x]==0:
                    check[next_y][next_x] = num
                    queue.append((next_y, next_x))
                    cnt += 1
    return cnt

n = int(input())
MAP = [list(map(int, input())) for _ in range(n)]
check = [[0]*n for _ in range(n)]

number = 0
result = []

for i in range(n):
    for j in range(n):
        if not check[i][j] and MAP[i][j] != 0:
            number += 1
            c = bfs(i,j,number)
            result.append(c)

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

댓글

이 블로그의 인기 게시물

[python]섬의 둘레구하기

백트래킹으로 부분집합구하기(Get Powerset usiing Backtracking)

[Python]DFS를 이용한 부분집합 구현