문제 링크 - https://programmers.co.kr/learn/courses/30/lessons/1844
from collections import deque
def solution(maps):
def bfs(x, y):
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
queue = deque()
queue.append((x, y))
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx < 0 or nx >=len(maps) or ny < 0 or ny >= len(maps[0]):
continue
if maps[nx][ny] == 0:
continue
if maps[nx][ny] == 1:
maps[nx][ny] = maps[x][y] + 1
queue.append((nx, ny))
return maps[len(maps)-1][len(maps[0])-1]
if bfs(0, 0) == 1:
return -1
else:
return bfs(0, 0)
from collections import deque
d = [[1,0], [-1, 0], [0,1], [0,-1]]
def solution(maps):
r = len(maps)
c = len(maps[0])
table = [[-1 for _ in range(c)] for _ in range(r)]
q = deque()
q.append([0,0])
table[0][0] = 1
while q:
y, x = q.popleft()
for i in range(4):
ny = y + d[i][0]
nx = x + d[i][1]
if -1<ny<r and -1<nx<c:
if maps[ny][nx] == 1:
if table[ny][nx] == -1:
table[ny][nx] = table[y][x] + 1
q.append([ny, nx])
answer = table[-1][-1]
return answer