문제
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2F11a0ba79-2c2b-4137-8559-5784794beb0e%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-06%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%204.00.56.png)
풀이
- 시작노드부터 인접한 노드의 차례대로 그래프를 탐색해야 하는 문제이기 때문에 BFS 알고리즘으로 접근하였다.
- BFS알고리즘을 활용하기 위해 deque 라이브러리로 queue를 구현하였다.
코드
from collections import deque
n, m = map(int, input().split())
graph = [list(map(int, input())) for i in range(n)]
dx = [-1, 0, 0, 1]
dy = [0, -1, 1, 0]
def bfs(x, y):
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 >= n or ny < 0 or ny >= m:
continue
if graph[nx][ny] == 0:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
return graph[n - 1][m - 1]
if __name__ == '__main__':
print(dfs(0, 0))
결과
![](https://velog.velcdn.com/images%2Fcosmos%2Fpost%2Fe2b77ae5-c87a-43eb-b11a-69e60174c664%2F%E1%84%89%E1%85%B3%E1%84%8F%E1%85%B3%E1%84%85%E1%85%B5%E1%86%AB%E1%84%89%E1%85%A3%E1%86%BA%202022-02-06%20%E1%84%8B%E1%85%A9%E1%84%92%E1%85%AE%204.00.37.png)
출처
boj 2178