2178. 미로 탐색
업데이트 시간 : 2023-02-21 08:39:45 +0000[Silver I] 미로 탐색 - 2178
성능 요약
메모리: 34244 KB, 시간: 80 ms
분류
너비 우선 탐색(bfs), 그래프 이론(graphs), 그래프 탐색(graph_traversal)
문제 설명
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)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
입력
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
출력
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
💡 Solutions
📄 미로 탐색.py
from collections import deque
dx = [0,0,-1,1]
dy = [1,-1,0,0]
def checkNstart(mat, type):
is_travel = [[False for _ in range(N)] for _ in range(N)]
for i in range(N):
for j in range(N):
if mat[i][j] == '2':
if type == 'bfs':
rlt = bfs(mat, is_travel, i , j)
return rlt
if type == 'dfs':
is_travel[i][j] = True
rlt = set()
dfs(mat, is_travel, i, j, 0, rlt)
return 0 if len(rlt) == 0 else min(rlt)
def dfs(mat, is_travel, i, j, depth, rlt:set):
if mat[i][j] == '3':
rlt.add(depth-1)
return
for k in range(4):
nx = i + dx[k]
ny = j + dy[k]
if nx < 0 or ny < 0 or nx >= N or ny >= N: continue
if mat[nx][ny] == '1' or is_travel[nx][ny] == True: continue
is_travel[nx][ny] = True
dfs(mat, is_travel, nx, ny, depth+1, rlt)
is_travel[nx][ny] = False
def bfs(mat, is_travel, i, j):
que = deque()
is_travel[i][j] = True
que.append((i,j, 1))
while que:
x, y, cnt = que.popleft()
if x == N-1 and y == M-1:
return cnt
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if nx < 0 or ny < 0 or nx >= N or ny >= M: continue
if mat[nx][ny] == '0' or is_travel[nx][ny] == True: continue
is_travel[nx][ny] = True
que.append((nx,ny,cnt+1))
return 0
N, M = map(int,input().split())
matrix = [list(input()) for _ in range(N)]
is_travel = [[False for _ in range(M)] for _ in range(N)]
print(bfs(matrix, is_travel, 0 , 0))