👨‍🏫ps/❄️프로그래머스

[프로그래머스] 무인도 여행 [python]

peacekim 2023. 4. 2. 21:15
반응형

문제

간단한 BFS 문제였다. X가 아닌 지점에서 BFS를 돌리고, 방문 여부를 체크한 후, X가 아닌 곧 중에 방문하지 않은 곳에서 또 다시 BFS를 돌리면 된다.

코드

def solution(maps):
    answer = []
    visited = [[False] * len(maps[i]) for i in range(len(maps))]
    for i in range(len(maps)):
        for j in range(len(maps[i])):
            if visited[i][j] == False and maps[i][j] != "X":
                answer.append(bfs(visited,i,j,maps))
    if len(answer) == 0:
        answer.append(-1)
    answer.sort()
    return answer

def bfs(visited, i,j, maps):
    mX = [0,1,-1,0]
    mY = [1,0,0,-1]
    queue = [[i,j]]
    visited[i][j] = True
    cnt = 0
    while queue:
        
        x, y = queue.pop(-1)
        cnt += int(maps[x][y])
        for k in range(4):
            nX = x + mX[k]
            nY = y + mY[k]
            if nX < 0 or nX >= len(maps) or nY < 0 or nY >= len(maps[0]) or visited[nX][nY] or maps[nX][nY] == "X":
                continue
            queue.append([nX,nY])
            visited[nX][nY] = True
        
    return cnt
"""
BFS로 구하면 될 듯
"""
반응형