본문 바로가기
PS/DFS_BFS

[백준] 2667번: 단지번호붙이기 파이썬

by 3급우사기 2024. 6. 25.

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

bfs로 탐색할때마다 갯수 세고, 집 수 세면 끝.

import sys
from collections import deque

def bfs(x,y):
  q = deque([(x,y)])
  arr[x][y] = -1
  house_count = 1
  while q:
    x,y = q.popleft()
    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]
      if 0 <= nx < n and 0 <= ny < n:
        if arr[nx][ny] == 1:
          arr[nx][ny] = -1
          house_count += 1
          q.append((nx,ny))
  return house_count


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

n = int(sys.stdin.readline())
arr = [list(map(int, list(sys.stdin.readline().strip()))) for _ in range(n)]
count = 0
house = []
for i in range(n):
  for j in range(n):
    if arr[i][j] == 1:
      count += 1
      house.append(bfs(i,j))
house.sort()
print(count)
for i in house:
  print(i)

 

bfs문제는 많이 나오니까 

관련 문제를 익숙해질때까지 많이 풀어야겠다.