728x90
출처 : https://www.acmicpc.net/problem/2178
< 초기설정 >
n, m = map(int, input().split())
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
graph = []
for i in range(n):
graph.append(list(map(int, input())))
count = 0
queue = [[0, 0]]
< bfs 정의 >
def bfs():
while queue:
a, b = queue.pop(0)
for i in range(4):
x = a + dx[i]
y = b + dy[i]
if 0 <= x < n and 0 <= y < m and graph[x][y] == 1:
graph[x][y] = graph[a][b] + 1
queue.append([x, y])
< 답 출력 >
bfs()
print(graph[-1][-1])
< 전체코드 >
n, m = map(int, input().split())
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
graph = []
for i in range(n):
graph.append(list(map(int, input())))
count = 0
queue = [[0, 0]]
def bfs():
while queue:
a, b = queue.pop(0)
for i in range(4):
x = a + dx[i]
y = b + dy[i]
if 0 <= x < n and 0 <= y < m and graph[x][y] == 1:
graph[x][y] = graph[a][b] + 1
queue.append([x, y])
bfs()
print(graph[-1][-1])
728x90
'코딩' 카테고리의 다른 글
[BOJ] 백준 2667 파이썬 - 단지번호 붙이기 (0) | 2021.11.17 |
---|