*문제 출처는 프로그래머스에 있습니다.
문제 제목: 미로 탈출 (2단계)
문제 사이트: https://school.programmers.co.kr/learn/courses/30/lessons/159993
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명

나의 풀이
from collections import deque
def bfs(maps, start_pos, target):
rows, cols = len(maps), len(maps[0])
visited = [[False] * cols for _ in range(rows)]
dq = deque()
dq.append((*start_pos, 0)) # (y, x, distance)
visited[start_pos[0]][start_pos[1]] = True
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while dq:
y, x, dist = dq.popleft()
if maps[y][x] == target:
return dist
for dy, dx in directions:
ny, nx = y + dy, x + dx
if 0 <= ny < rows and 0 <= nx < cols:
if not visited[ny][nx] and maps[ny][nx] != 'X':
visited[ny][nx] = True
dq.append((ny, nx, dist + 1))
return -1 # target에 도달하지 못한 경우
def solution(maps):
maps = [list(row) for row in maps]
# 시작점, 레버, 출구 위치 찾기
for i in range(len(maps)):
for j in range(len(maps[0])):
if maps[i][j] == 'S':
start = (i, j)
elif maps[i][j] == 'L':
lever = (i, j)
elif maps[i][j] == 'E':
end = (i, j)
# 두 단계로 나누어 BFS 실행
to_lever = bfs(maps, start, 'L')
to_end = bfs(maps, lever, 'E')
if to_lever == -1 or to_end == -1:
return -1
return to_lever + to_end

※ 알아야 할 것
여기서 *는 참조가 아닌 언패킹을 말합니다!
start_pos = (2, 3)
dq.append((*start_pos, 0))
# 결과 → dq.append((2, 3, 0))'Coding Test > 프로그래머스-Python' 카테고리의 다른 글
| Programmers / 상담원 인원 / Python (0) | 2025.11.13 |
|---|---|
| Programmers / 리코쳇 로봇 / Python (0) | 2025.09.09 |
| Programmers / N-Queen / Python (0) | 2025.03.31 |
| Programmers / 숫자 카드 나누기 / Python (0) | 2025.03.27 |
| Programmers / 전력망을 둘로 나누기 / Python (0) | 2025.03.26 |