본문 바로가기

알고리즘/test

Python) 프로그래머스 - 게임 맵 최단거리

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

실행코드:

from collections import deque

def solution(maps):
    answer = -1
    row = len(maps)
    col = len(maps[0])
    
    visited = [[False] * col for _ in range(row)]
    
    delta = [(1,0), (-1,0),(0,1),(0,-1)]
    
    queue = deque()
    queue.append((0,0,1))
    
    while queue:
        cur_r,cur_c,cur_len = queue.popleft()
        if cur_r == row - 1 and cur_c == col - 1:
            answer = cur_len
            break
        for dr, dc in delta:
            next_r = cur_r + dr
            next_c = cur_c + dc
            if next_r >= 0 and next_r < row and next_c >= 0 and next_c < col:
                if maps[next_r][next_c] == 1 and not visited[next_r][next_c]:
                    queue.append((next_r, next_c, cur_len + 1))
                    visited[next_r][next_c] = True
    return answer

풀이:

전형적인 BFS를 이용하여 풀이를 해 보았습니다.

1.maps와 크기가 같은 False로 채운 visited함수를 선언.

2.상하좌우 이동시킬 delta를 선언.

3.while문으로 BFS알고리즘 실행.

'알고리즘 > test' 카테고리의 다른 글

Python) 프로그래머스 - 미로 탈출  (1) 2023.03.14
Python) 프로그래머스 - 롤케이크 자르기  (0) 2023.03.14
Maximum Depth of Binary Tree  (0) 2023.03.07
LIFO - example 2  (0) 2023.03.06
LIFO - example 1  (0) 2023.03.03