문제
코드
from collections import deque
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
def bfs(x: int, y: int, maps: list, visited: list):
queue = deque()
queue.append([x, y])
visited[x][y] = True
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < len(maps) and 0 <= ny < len(maps[0]) and visited[nx][ny] == False and maps[nx][ny] == 1:
visited[nx][ny] = True
maps[nx][ny] = maps[x][y] + 1
queue.append([nx, ny])
return maps[len(maps)-1][len(maps[0])-1]
def solution(maps: list) -> int:
visited = [[False] * len(maps[0]) for _ in range(len(maps))]
answer = bfs(0, 0, maps, visited)
return answer if answer != 1 else -1
if __name__ == '__main__':
print(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]))
print(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]]))
결과
출처 & 깃허브
programmers
깃허브