forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path11.py
More file actions
40 lines (36 loc) ยท 1.28 KB
/
11.py
File metadata and controls
40 lines (36 loc) ยท 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from collections import deque
# N, M์ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์ฌ ์
๋ ฅ ๋ฐ๊ธฐ
n, m = map(int, input().split())
# 2์ฐจ์ ๋ฆฌ์คํธ์ ๋งต ์ ๋ณด ์
๋ ฅ ๋ฐ๊ธฐ
graph = []
for i in range(n):
graph.append(list(map(int, input())))
# ์ด๋ํ ๋ค ๊ฐ์ง ๋ฐฉํฅ ์ ์ (์, ํ, ์ข, ์ฐ)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# BFS ์์ค์ฝ๋ ๊ตฌํ
def bfs(x, y):
# ํ(Queue) ๊ตฌํ์ ์ํด deque ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
queue = deque()
queue.append((x, y))
# ํ๊ฐ ๋น ๋๊น์ง ๋ฐ๋ณตํ๊ธฐ
while queue:
x, y = queue.popleft()
# ํ์ฌ ์์น์์ 4๊ฐ์ง ๋ฐฉํฅ์ผ๋ก์ ์์น ํ์ธ
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]
# BFS๋ฅผ ์ํํ ๊ฒฐ๊ณผ ์ถ๋ ฅ
print(bfs(0, 0))