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문제는 많이 나오니까
관련 문제를 익숙해질때까지 많이 풀어야겠다.
'PS > DFS_BFS' 카테고리의 다른 글
[백준] 10026번: 적록색맹 파이썬 (0) | 2024.06.25 |
---|---|
[백준]4179번: 불! 파이썬 (0) | 2024.06.25 |
[백준] 7569번: 토마토(3차원) 파이썬 (0) | 2024.06.24 |
[백준] 24483번, 24484번 : 알고리즘 수업 - 깊이 우선 탐색 5, 6 파이썬 (0) | 2024.06.22 |
[백준] 24481번, 24482번 : 알고리즘 수업 - 깊이 우선 탐색 3, 4 파이썬 (0) | 2024.06.22 |