import sys
sys.setrecursionlimit(100000)
def solution(maps):
answer = []
direction = [[0,0],[1,0], [-1,0], [0,1], [0,-1]]
def dfs(x, y, cnt):
for d in direction:
n_x, n_y = x+d[0], y+d[1]
if 0 <= n_x < l_x and 0 <= n_y < l_y:
if maps[n_x][n_y] != 'X' and not visited[n_x][n_y]:
visited[n_x][n_y] = True
cnt = dfs(n_x, n_y, cnt + int(maps[n_x][n_y]))
return cnt
l_x, l_y = len(maps), len(maps[0])
visited = [[False] * l_y for _ in range(l_x)]
for i in range(l_x):
for j in range(l_y):
t = 0
if not visited[i][j] and maps[i][j] != 'X':
t = dfs(i,j,0)
if t:
answer.append(t)
if len(answer):
answer.sort()
return answer
else:
return[-1]
dfs혹은 bfs로 해결 가능한 문제
dfs로 풀 때는 재귀 조건때문에 setrecursionlimit를 설정해줘야한다.