주어지는 n x m 크기의 2차원 배열로 맵의 정보가 주어지고 (1,1)에서 (n,m)까지 가는 최단거리를 구하는 문제입니다. 맵의 정보 중 1이면 갈 수 있고 0이면 벽이라서 갈 수 없습니다.
저는 이 문제를 BFS 너비 우선 탐색을 이용해서 문제를 해결하였습니다.
코드를 보면
from collections import deque
def solution(maps):
visited = [[False for i in range(len(maps[0]))] for i in range(len(maps))]
queue = deque()
index1 = 0
index2 = 0
answer = 1
queue.append([index1,index2,answer])
visited[0][0] = True
while queue:
index1,index2,answer = queue.popleft()
if index1 == len(maps)-1 and index2 == len(maps[0])-1:
break
answer+=1
if index2+1 < len(maps[0]): # x좌표 + 움직임
if maps[index1][index2+1] == 1:
if visited[index1][index2+1] == False:
visited[index1][index2+1] = True # 미 방문시 방문처리
queue.append([index1,index2+1,answer])
if index2-1 >= 0 : # x 좌표 - 움직임
if maps[index1][index2-1] == 1 :
if visited[index1][index2-1] == False:
visited[index1][index2-1] = True # 미 방문시 방문처리
queue.append([index1,index2-1,answer])
if index1+1 < len(maps) : # y 좌표 + 움직임
if maps[index1+1][index2]==1:
if visited[index1+1][index2] == False:
visited[index1+1][index2] = True # 미 방문시 방문처리
queue.append([index1+1,index2,answer])
if index1-1 >= 0 : # y좌표 - 움직임
if maps[index1-1][index2] == 1:
if visited[index1-1][index2] == False:
visited[index1-1][index2] = True # 미 방문시 방문처리
queue.append([index1-1,index2,answer])
if index1 != len(maps)-1 or index2 != len(maps[0])-1:
answer = -1
return answer
위의 코드와 같이 각각 움직일 수 있는 동,서,남,북의 경우를 모두 체크해 움직일 수 있다면 방문처리를 하고 움직인 인덱스를 queue에 넣어주게 됩니다. 방문처리를 하는 경우는 이미 지나간 곳을 다시 지나가지 않게 하기 위한 것입니다. 최소 거리를 구해야 하기 때문에 while문을 돌다가 인덱스 값이 (n-1,m-1)이 된다면 while문을 빠져 나옵니다. n-1,m-1을 한 이유는 인덱스 시작을 0부터 시작했기 때문입니다. 만약 (n-1,m-1) 자리나 바로 붙어 있는 주변에 벽이 있다면 (n-1,m-1) 자리에 도달하지 못합니다. queue에 있는 모든 요소를 꺼냈는데 인덱스 값이 (n-1,m-1)이 아니라면 도달하지 못한 것이기 때문에 -1을 반환 합니다.