File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ import sys
2+ from collections import deque
3+ input = sys .stdin .readline
4+
5+ # 방향 벡터: 상, 하, 좌, 우
6+ dx = [- 1 , 1 , 0 , 0 ]
7+ dy = [0 , 0 , - 1 , 1 ]
8+
9+ def bfs (start_x , start_y ):
10+ queue = deque ()
11+ queue .append ((start_x , start_y ))
12+ graph [start_x ][start_y ] = 0 # 방문 처리
13+ house_count = 1 # 단지 내 집 수
14+
15+ while queue :
16+ x , y = queue .popleft ()
17+ for i in range (4 ): # 상하좌우 탐색
18+ nx , ny = x + dx [i ], y + dy [i ]
19+
20+ # 좌표가 유효한지 확인
21+ if 0 <= nx < n and 0 <= ny < n and graph [nx ][ny ] == 1 :
22+ graph [nx ][ny ] = 0 # 방문 처리
23+ queue .append ((nx , ny ))
24+ house_count += 1
25+ return house_count
26+
27+ # 입력
28+ n = int (input ())
29+ graph = [list (map (int , input ().strip ())) for _ in range (n )]
30+
31+ result = []
32+
33+ # 모든 좌표 순회하며 BFS 수행
34+ for i in range (n ):
35+ for j in range (n ):
36+ if graph [i ][j ] == 1 :
37+ result .append (bfs (i , j ))
38+
39+ # 결과 출력
40+ result .sort ()
41+ print (len (result ))
42+ for count in result :
43+ print (count )
You can’t perform that action at this time.
0 commit comments