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

풀이방법:

  • bfs를 통해 문제를 해결하였습니다.
  • direction 배열을 통해 이동할 수 있는 방향을 지정해주었습니다.
  • 마지막으로, 가고자하는 위치의 값이 1(초기 값)이거나 현재 가는 경로가 더 가깝다면 갱신 될 수 있도록 하였습니다.

풀이코드:

from collections import deque
def solution(maps):
    q = [(0,0)]
    direction = [(0,1),(0,-1),(1,0),(-1,0)]

    while q:
        x,y = q.pop(0)
        for i,j in direction:
            nx = x + i
            ny = y + j
            if nx < 0 or nx >= len(maps) or ny < 0 or ny >= len(maps[0]) :
                continue

            if maps[nx][ny] == 1 or maps[x][y]+1 < maps[nx][ny]:
                maps[nx][ny] = maps[x][y]+1
                q.append((nx,ny))

    return -1 if maps[len(maps)-1][len(maps[0])-1] == 1 else maps[len(maps)-1][len(maps[0])-1]

+ Recent posts