💡코딩테스트/프로그래머스

[python | 프로그래머스] LV.2 게임 맵 최단거리

두_두 2023. 4. 5. 15:57

문제

 

프로그래머스

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

programmers.co.kr

게임 맵의 상태 maps가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1을 return 해주세요.

 

풀이

첫번째 접근 ➡️ DFS

    def dfs(x, y):
        visited[x][y] = 1

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < len(maps) and 0 <= ny < len(maps[0]) and visited[nx][ny] == 0 and maps[nx][ny] == 1:
                    maps[nx][ny] = maps[x][y] + 1

                dfs(nx, ny)

시간 초과 문제로 DFS보다 시간복잡도가 더 낮은 BFS로 구현하기로 함!

 

두번째 접근 ➡️ BFS

    def bfs(x, y):
        queue = deque()
        queue.append((x,y))
        visited[x][y] = 1

        while queue:
            x, y = queue.popleft()
            for i in range(4):
                nx, ny = x + dx[i], y + dy[i]
                if 0 <= nx < len(maps) and 0 <= ny < len(maps[0]) and visited[nx][ny] == 0 and maps[nx][ny] == 1:
                    queue.append((nx, ny))
                    visited[nx][ny] = 1
                    maps[nx][ny] = maps[x][y] + 1

 

전체 코드

from collections import deque

def solution(maps):
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]

    visited = [[0 for _ in range(len(maps[0]))] for _ in range(len(maps))]

    def bfs(x, y):
        queue = deque()
        queue.append((x,y))
        visited[x][y] = 1

        while queue:
            x, y = queue.popleft()
            for i in range(4):
                nx, ny = x + dx[i], y + dy[i]
                if 0 <= nx < len(maps) and 0 <= ny < len(maps[0]) and visited[nx][ny] == 0 and maps[nx][ny] == 1:
                    queue.append((nx, ny))
                    visited[nx][ny] = 1
                    maps[nx][ny] = maps[x][y] + 1

    bfs(0, 0)

    return -1 if maps[-1][-1] == 1 else maps[-1][-1]
728x90