백준 알고리즘 2178. 미로 탐색

2024. 3. 12. 20:22코딩 테스트/백준

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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

전체 코드

import sys
import collections


def solution(mat):
    def is_promising(mat, x, y, width, height):
        return 0 <= x < width and 0 <= y < height and mat[y][x] == '1'

    def bfs(mat, x, y, width, height):
        queue = collections.deque()
        queue.append((x, y, 0))
        min_count = sys.maxsize

        while queue:
            (x, y, count) = queue.popleft()
            if is_promising(mat, x, y, width, height):
                mat[y][x] = '0'
                queue.append((x + 1, y, count + 1))
                queue.append((x - 1, y, count + 1))
                queue.append((x, y - 1, count + 1))
                queue.append((x, y + 1, count + 1))

            if x == (width - 1) and y == (height - 1):
                count += 1
                min_count = min(min_count, count)
                break
        return min_count

    return bfs(mat, 0, 0, len(mat[0]), len(mat))


n, m = map(int, input().split())
mat = []
for _ in range(n):
    mat.append(list(input()))

print(solution(mat))