PS/백준

[백준] (2178) 미로 탐색 [Python]

munsik22 2025. 3. 29. 14:22

문제 링크

https://www.acmicpc.net/problem/2178

문제

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

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

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

  • 입력
    첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
  • 출력
    첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
예제 입력 예제 출력
4 6
101111
101010
101011
111011
15





코드

import sys
input = sys.stdin.readline
from collections import deque

n, m = map(int, input().split())
maze = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n):
    s = input()
    for j in range(m):
        if s[j] == '1':
            maze[i][j] = 1

visited = set()
queue = deque()
queue.append((0,0))

while queue:
    v = queue.popleft()
    
    if v not in visited:
        visited.add(v)
        x, y = v[0], v[1]

        if x > 0 and maze[x-1][y] > 0 and (x-1, y) not in visited and (x-1, y) not in queue:
            maze[x-1][y] += maze[x][y]
            queue.append((x-1, y))
            
        if x < n-1 and maze[x+1][y] > 0 and (x+1,y) not in visited and (x+1, y) not in queue:
            maze[x+1][y] += maze[x][y]
            queue.append((x+1, y))
            
        if y > 0 and maze[x][y-1] > 0 and (x,y-1) not in visited and (x, y-1) not in queue:
            maze[x][y-1] += maze[x][y]
            queue.append((x, y-1))
            
        if y < m-1 and maze[x][y+1] > 0 and (x,y+1) not in visited and (x, y+1) not in queue:
            maze[x][y+1] += maze[x][y]
            queue.append((x, y+1))
    
print(maze[n-1][m-1])

조건식이 상당히 길어서 구현하는 데에 애로사항이 있었다.😇