2667번: 단지번호붙이기
<그림 1>과 같이 정사각형 모양의 지도가 있다. 1은 집이 있는 곳을, 0은 집이 없는 곳을 나타낸다. 철수는 이 지도를 가지고 연결된 집들의 모임인 단지를 정의하고, 단지에 번호를 붙이려 한다. �
www.acmicpc.net
# 단지번호 붙이기
# https://www.acmicpc.net/problem/2667 (그래프, BFS)
from collections import deque
def bfs(x, y, area):
dq = deque([(x, y)])
while dq:
x, y = dq.popleft()
if mp[x][y] == 0 or visited[x][y]:
continue
global count
count += 1
visited[x][y] = area
direction = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for e in direction:
nx, ny = x + e[0], y + e[1]
if 0 <= nx < n and 0 <= ny < n and mp[nx][ny] == 1 and not visited[nx][ny]:
dq.append([nx, ny])
return count
n = int(input())
mp = [list(map(int, input())) for _ in range(n)]
visited = [[0] * n for _ in range(n)]
area = 1
count_list = []
for num in range(n * n):
i, j = num // n, num % n
count = 0
if bfs(i, j, area) > 0:
area += 1
count_list.append(count)
print(len(count_list))
print("\n".join(map(str, count_list)))
'BOJ 알고리즘 (T아카데미)' 카테고리의 다른 글
13116번: 30번 (그래프, 부모배열) (0) | 2020.10.01 |
---|---|
2644번: 촌수계산 (그래프, BFS) (0) | 2020.10.01 |
11866번: 요세푸스 문제 0 (구현, 큐) - Tacademy (0) | 2020.10.01 |
9012번: 괄호 (구현, 스택) - Tacademy (0) | 2020.10.01 |
11729번: 하노이탑 (구현, 재귀) - Tacademy (0) | 2020.10.01 |