Photo by Pietro Mattia on Unsplash
dfs 코드
n = int(input())
graph = []
answer = []
for _ in range(n):
graph.append(list(map(int, input())))
def dfs(x,y):
if y < 0 or y >= n or x< 0 or x >= n:
return False
if graph[x][y] == 1:
global cnt
cnt += 1
graph[x][y] = 0
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
return True
return False
result = 0
cnt = 0
for i in range(n):
for j in range(n):
if dfs(i,j) == True:
answer.append(cnt)
result+=1
cnt = 0
answer.sort()
print(result)
for i in range(result):
print(answer[i])
bfs 코드
from collections import deque
n = int(input())
graph = []
answer = []
for _ in range(n):
graph.append(list(map(int, input())))
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(graph, x, y):
queue = deque()
queue.append((x,y))
graph[x][y] = 0
cnt = 1
while queue:
check_x, check_y = queue.popleft()
for i in range(4):
nx = check_x + dx[i]
ny = check_y + dy[i]
if nx < 0 or nx >= n or ny < 0 or ny >= n:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = 0
queue.append((nx,ny))
cnt+=1
return cnt
complex_cnt = []
for i in range(n):
for j in range(n):
if graph[i][j] == 1:
complex_cnt.append(bfs(graph,i,j))
complex_cnt.sort()
print(len(complex_cnt))
for i in range(len(complex_cnt)):
print(complex_cnt[i])
from collections import deque
def solution(maps):
n = len(maps)
m = len(maps[0])
if n == 1 and m == 1:
return 1
dx = [0 ,0, 1, -1]
dy = [1, -1, 0, 0]
queue = deque()
queue.append((0, 0))
while queue:
check_x, check_y = queue.popleft()
for i in range(4):
nx = check_x + dx[i]
ny = check_y + dy[i]
if -1< nx < n and -1 < ny < m:
if maps[nx][ny] == 1:
maps[nx][ny] = maps[check_x][check_y]+1
queue.append((nx,ny))
if maps[-1][-1] ==1:
return -1
return maps[-1][-1]