본문 바로가기
Programming/Programmers

[프로그래머스] 게임 맵 최단거리(Python)

by 데이터현 2021. 10. 31.

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

 

코딩테스트 연습 - 게임 맵 최단거리

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr

 

전형적인 BFS 문제다

 

나의 풀이

from collections import deque

def solution(maps):
    n,m = len(maps), len(maps[0])
    visited = [[0]*m for _ in range(n)]
    visited[0][0]=True
    move = [(1,0),(-1,0),(0,1),(0,-1)]
    answer = 1
    queue = deque()
    queue.append((0,0,answer))
    while queue:
        i, j, answer = queue.popleft()
        for mov in move:
            x, y = i + mov[0], j + mov[1]
            if 0<= x <n and 0<= y <m:
                if visited[x][y] ==True:
                    continue
                if maps[x][y] == 1:
                    if x == n-1 and y == m-1 :
                        return answer+1
                    else:
                        visited[x][y] = True
                        queue.append((x,y,answer+1))
    return -1

댓글