https://www.acmicpc.net/problem/2667
연결되어 있는 Connected Component - DFS
인접 행렬 adjMatrix
(입력 및 선언)
(dfs 함수)
(단지 찾기)
(최종 출력)
n = int(input())
adjMatrix = []
visited = [[0 for _ in range(n)] for _ in range(n)]
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
apartCnt = 0
danji = 0
ans = []
for i in range(n) :
adjMatrix.append(list(map(int, input())))
# dfs(num) - Recursion
def dfs(y, x) :
global apartCnt
for i in range(4) :
ny = y + dy[i]
nx = x + dx[i]
if ny < 0 or nx < 0 or ny >= n or nx >= n :
continue
if adjMatrix[ny][nx] == 0 :
continue
if visited[ny][nx] != 0 :
continue
visited[ny][nx] = 1
apartCnt += 1
dfs(ny, nx)
for i in range(n) :
for j in range(n) :
if adjMatrix[i][j] == 0 : continue
if visited[i][j] != 0 : continue
danji += 1
apartCnt += 1
visited[i][j] = True
dfs(i, j)
ans.append(apartCnt)
apartCnt = 0
ans.sort()
print(danji)
for i in ans :
print(i)
(+ 2023/10/11 add)
from collections import deque
n = int(input())
adjMatrix = []
visited = [[0 for _ in range(n)] for _ in range(n)]
dy = [-1, 0, 1, 0]
dx = [0, 1, 0, -1]
bfsQueue = deque([])
cnt = 0
ans = []
for i in range(n) :
adjMatrix.append(list(map(int, input())))
def bfs():
apartCnt = 1
while bfsQueue:
curY, curX = bfsQueue.popleft()
for i in range(4):
ny = curY + dy[i]
nx = curX + dx[i]
if 0 <= ny < n and 0 <= nx < n:
if adjMatrix[ny][nx] == 1 and visited[ny][nx] == 0:
visited[ny][nx] = 1
bfsQueue.append([ny, nx])
apartCnt += 1
ans.append(apartCnt)
for i in range(n):
for j in range(n):
if adjMatrix[i][j] == 1 and visited[i][j] == 0:
bfsQueue.append([i, j])
visited[i][j] = 1
bfs()
cnt += 1
ans.sort()
print(cnt)
for i in ans:
print(i)