알고리즘/프로그래머스 문제풀이

[프로그래머스] lv.2 무인도 여행 python 풀이

감자156 2023. 5. 13. 21:57
반응형

섬의 크기 찾는 문제의 응용, bfs와 공용 visited 배열을 이용해 풀이함.

bfs 개념)

https://cccaaa.tistory.com/22

 

넓이우선탐색(bfs) 동작과정

"시작점 (0, 0) 도착점 (1, 2)일 때, 2차원 배열 (3X3)에서 시작점으로부터 도착점까지의 최단거리를 찾아라"는 문제를 푸는 과정입니다. 우선 2차원 배열과 queue를 선언합니다. 본인이 설정해 둔 move

cccaaa.tistory.com

문제)

https://school.programmers.co.kr/learn/courses/30/lessons/154540

 

코드)

import collections

def bfs(x,y,maps,visited):
    moves = {(-1,0),(0,1),(1,0),(0,-1)}
    
    q = collections.deque()
    q.append((x,y))
    
    visited[x][y] = 1 #visited
    
    days = int(maps[x][y])
    while q: 
        x,y = q.popleft()
        
        for tx, ty in moves:
            nx = x + tx
            ny = y + ty
            
            if 0<=nx<len(maps) and 0<=ny<len(maps[0]):
                if maps[nx][ny] != 'X' and visited[nx][ny] != 1:
                    q.append((nx,ny))
                    visited[nx][ny] = 1
                    days += int(maps[nx][ny])
                
    return days
                

def solution(maps):
    total = []
    visited = [[0 for _ in range(len(maps[0]))] for _ in range(len(maps))]
    for i in range(len(maps)):
        for j in range(len(maps[0])):
            if maps[i][j] != 'X' and visited[i][j] == 0:
                total.append(bfs(i,j,maps,visited))

    if total:
        return sorted(total)
    else: return [-1]
반응형