[Algorithm] 프로그래머스 '게임맵최단거리' (with python)

휴먼시아·2024년 10월 13일

Algorithm

목록 보기
5/5
post-thumbnail

📝 문제


💡 아이디어

  1. 최단거리 탐색 - BFS
  1. directions 변수 지정(상히좌우 이동)
  1. 현위치로부터 탐색할 사항

    a. 상하좌우 이동 가능한가? (벽 확인🚪)
    b. 이미 방문한 곳인가?


🔓 풀이

from collections import deque
def solution(maps):

    directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]

    n, m = len(maps), len(maps[0])
    queue = deque([(0, 0)])

    while queue:
        x, y = queue.popleft()

        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            
            if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] == 1:
                maps[nx][ny] += maps[x][y]
                queue.append((nx, ny))

    return maps[n-1][m-1] if maps[n-1][m-1] > 1 else -1


글로벌소프트웨어캠퍼스와 교보DTS가 함께 진행하는 챌린지입니다. #내맘대로TIL챌린지 #교보DTS #클라우드교육 #글로벌소프트웨어캠퍼스 #GSC신촌
profile
코(딩)찔찔이 성장기

0개의 댓글