[๋ฐฑ์ค-14497] ์ฃผ๋์ ๋(้ฃ) / Python
๐ Problem Solving/Baekjoon
https://www.acmicpc.net/problem/14497
14497๋ฒ: ์ฃผ๋์ ๋(้ฃ)
์ฃผ๋์ด๋ ํฌ๊ฒ ํ๊ฐ ๋ฌ๋ค. ์ฑ ์ ์๋ ์์ ๋ชฐ๋ ๋จน์ผ๋ ค๊ณ ์จ๊ฒจ๋ ์ด์ฝ๋ฐ๊ฐ ์ฌ๋ผ์ก๊ธฐ ๋๋ฌธ์ด๋ค. ์ฃผ๋์ด๋ ๋ฏธ์ณ ๋ ๋ฐ๊ธฐ ์์ํ๋ค. ์ฌ์ค, ์ง์ง๋ก ๋ฐ๊ธฐ ์์ํ๋ค. ‘์ฟต... ์ฟต...’ ์ฃผ๋์ด๋ ์ ํ์ ํ
www.acmicpc.net
import sys
from collections import deque
input = sys.stdin.readline
n, m = map(int, input().split())
x1, y1, x2, y2 = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(str, input().rstrip())))
distance = [[-1] * m for _ in range(n)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
queue = deque()
queue.append((x, y))
distance[x][y] = 0
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and distance[nx][ny] == -1:
if graph[nx][ny] == "1" or graph[nx][ny] == "#":
distance[nx][ny] = distance[x][y] + 1
queue.append((nx, ny))
elif graph[nx][ny] == "0":
distance[nx][ny] = distance[x][y]
queue.appendleft((nx, ny))
bfs(x1 - 1, y1 - 1)
print(distance[x2 - 1][y2 - 1])
ํด์ค
bfs๋ฅผ ์ฌ์ฉํด ํด๊ฒฐํ ๋ฌธ์ ๋ค. ์ ํ๋ฅผ ๋ธ ๋๋ง๋ค 0์ด๋ฉด ์ด์ ๊ฐ์ผ๋ก, 1์ด๋ฉด ์ด์ ๊ฐ์ +1 ๋ก ๋ฐ๋๋ค.
'๐ Problem Solving > Baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค-5972] ํ๋ฐฐ ๋ฐฐ์ก / Python (0) | 2021.07.02 |
---|---|
[๋ฐฑ์ค-18405] ๊ฒฝ์์ ์ ์ผ / Python (0) | 2021.07.02 |
[๋ฐฑ์ค-6118] ์จ๋ฐ๊ผญ์ง / Python (0) | 2021.07.02 |
[๋ฐฑ์ค-1743] ์์๋ฌผ ํผํ๊ธฐ / Python (0) | 2021.07.02 |
[๋ฐฑ์ค-1926] ๊ทธ๋ฆผ / Python (0) | 2021.07.01 |