[프그] BFS/DFS : 게임 맵 최단거리

yozzum·2022년 7월 13일
0

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

아이디어

간선의 길이(이동하는 셀의 거리)가 동일할때 최단거리는 BFS를 활용해 구할 수 있다.

내가 짠 코드

from collections import deque
def solution(maps):
    lenx = len(maps)
    leny = len(maps[0])

	# 상하좌우
    mx = [-1, 1, 0, 0] # 상하이동 (행)
    my = [0, 0, -1, 1] # 좌우이동 (열)
    
    q = deque()
    q.append((0,0)) # init curx, cury
    while q:
        curx, cury = q.popleft()
        for i in range(4):
            nx = curx + mx[i]
            ny = cury + my[i]
            if nx < 0 or ny < 0 or nx >= lenx or ny >= leny:
                continue
            if maps[nx][ny] == 1:
                q.append((nx, ny))
                maps[nx][ny] = maps[curx][cury] + 1
                if nx == lenx-1 and ny == leny-1:
                    return maps[nx][ny]
    return -1
profile
yozzum

0개의 댓글