본문 바로가기
Algorithm/programmers

[파이썬]programmers: 게임 맵 최단거리

by 갈잃자 2023. 3. 31.

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


dfs/bfs문제

 

아래 내용은 bfs로 구현한 내용이다.

from collections import deque
def solution(maps):
    n = len(maps)
    m = len(maps[0])
    visit = [[0]*m for _ in range(n)]
    directy = [-1,1,0,0]
    directx = [0,0,-1,1]
    def bfs(start):
        q = deque()
        q.append(start)

        while q:
            nowy, nowx, nowcnt = q.popleft()

            for i in range(4):
                dy = nowy + directy[i]
                dx = nowx + directx[i]

                if 0<=dy<len(maps) and 0<=dx<len(maps[0]):
                    if maps[dy][dx] == 0: continue
                    if visit[dy][dx] == 1: continue
                    if [dy, dx] == [len(maps)-1, len(maps[0])-1]:
                        return nowcnt +1
                    visit[dy][dx] =1
                    q.append((dy,dx,nowcnt +1))





    answer = bfs((0,0,1))

    if answer == None:
        answer = -1

    return answer

댓글