
너비 우선 탐색, 그래프 이론, 그래프 탐색
N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로로 이동하려 한다. 최단경로는 맵에서 가장 적은 개수의 칸을 지나는 경로를 말하는데, 이때 시작하는 칸과 끝나는 칸도 포함해서 센다.
만약에 이동하는 도중에 한 개의 벽을 부수고 이동하는 것이 좀 더 경로가 짧아진다면, 벽을 한 개 까지 부수고 이동하여도 된다.
한 칸에서 이동할 수 있는 칸은 상하좌우로 인접한 칸이다.
맵이 주어졌을 때, 최단 경로를 구해 내는 프로그램을 작성하시오.
첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000)이 주어진다. 다음 N개의 줄에 M개의 숫자로 맵이 주어진다. (1, 1)과 (N, M)은 항상 0이라고 가정하자.
첫째 줄에 최단 거리를 출력한다. 불가능할 때는 -1을 출력한다.
(1,1)에서 (N,M)까지 이동하는데 벽을 한개는 부숴도 될 때의 이동 최소 거리를 구하는 문제였다.
벽을 부수지 않고 이동하는 그룹, 벽을 한번 부수고 이동하는 그룹으로 나눠서 bfs를 진행함으로서 해결할 수 있었다.
import sys
def can_go(i, j):
temp_ = []
if i - 1 >= 0 and visited[i-1][j] == 0:
temp_.append([i-1, j])
if i + 1 < N and visited[i+1][j] == 0:
temp_.append([i+1, j])
if j - 1 >= 0 and visited[i][j-1] == 0:
temp_.append([i, j-1])
if j + 1 < M and visited[i][j+1] == 0:
temp_.append([i, j+1])
return temp_
def can_go_wall(i, j):
temp_ = []
if i - 1 >= 0 and wall_visited[i-1][j] == 0 and graph[i-1][j] == '0':
temp_.append([i-1, j])
if i + 1 < N and wall_visited[i+1][j] == 0 and graph[i+1][j] == '0':
temp_.append([i+1, j])
if j - 1 >= 0 and wall_visited[i][j-1] == 0 and graph[i][j-1] == '0':
temp_.append([i, j-1])
if j + 1 < M and wall_visited[i][j+1] == 0 and graph[i][j+1] == '0':
temp_.append([i, j+1])
return temp_
N, M = map(int, sys.stdin.readline().split())
if N == 1 and M == 1:
print(1)
sys.exit()
graph = [sys.stdin.readline().rstrip() for _ in range(N)]
visited = [[0 for _ in range(M)] for _ in range(N)]
wall_visited = [[0 for _ in range(M)] for _ in range(N)]
visited[0][0] = 1
wall_visited[0][0] = 1
go = [[0,0]]
crashed = []
result = 1
while go or crashed:
result += 1
temp = []
temp_ = []
for i, j in go:
for k, l in can_go(i, j):
visited[k][l] = 1
if graph[k][l] == '1':
wall_visited[k][l] = 1
temp_.append([k, l])
else:
temp.append([k, l])
go = temp
for i, j in crashed:
for k, l in can_go_wall(i, j):
wall_visited[k][l] = 1
temp_.append([k, l])
crashed = temp_
if visited[N-1][M-1] == 1 or wall_visited[N-1][M-1] == 1:
print(result)
sys.exit()
print(-1)