Skip to content

Commit e433e4c

Browse files
committed
[BOJ] 미로찾기 / 실버1 / 25분
https://www.acmicpc.net/problem/2178
1 parent 5c1a49e commit e433e4c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from collections import deque
2+
3+
4+
def bfs(graph, visited):
5+
dx = [-1, 1, 0, 0]
6+
dy = [0, 0, -1, 1]
7+
8+
queue = deque([(0, 0, 1)]) # (x, y, distance)
9+
visited[0][0] = 1
10+
11+
while queue:
12+
x, y, dist = queue.popleft()
13+
14+
if x == n - 1 and y == m - 1:
15+
return dist
16+
17+
for i in range(4):
18+
row = x + dx[i]
19+
col = y + dy[i]
20+
21+
if 0 <= row < n and 0 <= col < m and visited[row][col] == 0 and graph[row][col] == 1:
22+
visited[row][col] = 1
23+
queue.append((row, col, dist + 1))
24+
25+
return -1 # 목적지에 도달할 수 없는 경우
26+
27+
28+
n, m = map(int, input().split())
29+
graph = []
30+
visited = [[0] * m for _ in range(n)]
31+
32+
for _ in range(n):
33+
line = input()
34+
graph.append([int(char) for char in line])
35+
36+
min_answer = bfs(graph, visited)
37+
38+
print(min_answer)

0 commit comments

Comments
 (0)