개발/algorithm

[백준 2667번] 단지번호 붙이기 -python

zzi_on2 2022. 1. 25. 13:54

문제 링크

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

 

2667번: 단지번호붙이기

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

www.acmicpc.net

풀이 - 다시 품 

from collections import deque

dx = [ -1, 1, 0, 0 ]
dy = [0 ,0 , -1 ,1]

def bfs(i,j):
  # 단지 개수 저장 
  count = 1 
  queue = deque()
  queue.append((i,j))
  maps[i][j] = 0 

  while queue:
    x, y = queue.popleft()

    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]
      if 0<=nx < n and 0<= ny < n and maps[nx][ny] == 1:
        maps[nx][ny] = 0 
        queue.append((nx,ny))
        count += 1 
  
  return count 

n = int(input())

maps = []

for i in range(n):
  maps.append(list(map(int,input())))

result = []
for i in range(n):
  for j in range(n):
    if maps[i][j] == 1 :
      result.append(bfs(i,j))

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