Coding test(Python3)/BaeckJoon

[BOJ 2178번] 미로 탐색

녜잉 2024. 8. 3. 18:13

1. 문제

N×M크기의 배열로 표현되는 미로가 있다.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.

 


2. 문제 풀이

 

프로그래머스 게임 맵 최단 거리 문제와 쌍둥이 문제이다

https://nervertheless.tistory.com/172

 

[level 2] 게임 맵 최단거리

1. 문제 ROR 게임은 두 팀으로 나누어서 진행하며, 상대 팀 진영을 먼저 파괴하면 이기는 게임입니다. 따라서, 각 팀은 상대 팀 진영에 최대한 빨리 도착하는 것이 유리합니다.지금부터 당신은 한

nervertheless.tistory.com

 

import sys
from collections import deque

N, M = list(map(int, sys.stdin.readline().split()))
maps = []
for i in range(N):
    maps.append(list(map(int, sys.stdin.readline().rstrip())))
    
visited = set()
visited.add((0, 0))
queue = deque([(0, 0, 1)])
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]


while queue:
    
    x, y, count = queue.popleft()
    
    if x == N-1 and y == M-1:
        print(count)
        break
    
    for dx, dy in directions:
        
        nx, ny = x+dx, y+dy
        
        if 0<=nx<N and 0<=ny<M and maps[nx][ny] == 1 and (nx, ny) not in visited:
            queue.append((nx, ny, count+1))
            visited.add((nx,ny))