알고리즘 배우기
[프로그래머스] Lv 2. 게임 맵 최단거리
by cwin
2024. 7. 19.
def solution(maps):
answer = 0
#상,하,좌,우
X = len(maps[0])
Y = len(maps)
visited = [[False for _ in range(X)] for _ in range(Y)]
dx = [0,0,-1,1]
dy = [-1,1,0,0]
queue = []
def bfs(x, y):
visited[y][x] = True
queue.append([y, x])
while queue:
current = queue.pop(0)
y, x = current[0], current[1]
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if 0<= ny < Y and 0<= nx < X and maps[ny][nx] == 1:
if visited[ny][nx] == False:
visited[ny][nx] = True
queue.append([ny, nx])
maps[ny][nx] = maps[y][x] + 1
bfs(0, 0)
if maps[Y-1][X-1] == 1:
return -1
else:
return maps[Y-1][X-1]