본문 바로가기

알고리즘

[프로그래머스 고득점 Kit] (dfs/bfs) 게임 맵 최단거리

 

from collections import deque

def solution(maps):
    # global visited
    answer = 0
    n=len(maps)
    m=len(maps[0])
    # visited=[[0]*m for _ in range(n)]
    dx=[-1,1,0,0]
    dy=[0,0,-1,1]
    deq = deque()
    deq.append((0,0))
    # visited[0][0] = 1
    while deq:
        poped = deq.popleft()
        nx,ny = poped[0],poped[1]
        for i in range(4):
            x = nx+dx[i]
            y = ny+dy[i]
            
            if x<0 or x>=n or y<0 or y>=m:
                continue
            if maps[x][y] == 0:
                continue
            if maps[x][y] == 1:
                maps[x][y] = maps[nx][ny]+1
                deq.append((x,y))
        
    if maps[n-1][m-1] == 1:
        answer = -1
    else:
        answer = maps[n-1][m-1]
    
    
    return answer

 

가장빨리 도달하는 타일 개수 찾기 - bfs로 풀기

dx와 dy를 두고 문제 해결.

deque 활용법.

continue 조건 해결.

 

반응형