๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 2178๋ฒ
ํ์ด ๊ณผ์
์์ ์ง์ ์์ (N, M)
์ ๋ชฉํ ์ง์ ์ ๋๋ฌํ๊ธฐ ์ํ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ณ์ฐํ๋ BFS
๋ฌธ์ ์
๋๋ค.
๋ณ๋ค๋ฅธ ์ถ๊ฐ ์กฐ๊ฑด ์์ด ๊ธฐ๋ณธ์ ์ธ BFS
์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํํด์ฃผ๋ฉด ๋ฉ๋๋ค.
์ฝ๋
import sys
from collections import deque
N, M = list(map(int, sys.stdin.readline().split()))
board = [list(map(int, sys.stdin.readline().strip())) for _ in range(N)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs(x, y):
q = deque()
visit = [[0]*M for _ in range(N)]
q.append([x, y, 1])
visit[x][y] = 1
while q:
x, y, cost = q.popleft()
if x == N - 1 and y == M - 1:
return cost
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if not visit[nx][ny] and board[nx][ny]:
visit[nx][ny] = 1
q.append([nx, ny, cost + 1])
def solution():
ans = bfs(0, 0)
return ans
print(solution())
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 16926 - ๋ฐฐ์ด ๋๋ฆฌ๊ธฐ 1 (0) | 2021.04.13 |
---|---|
BOJ 15732 - ๋ํ ๋ฆฌ ์จ๊ธฐ๊ธฐ (0) | 2021.03.18 |
BOJ 6593 - ์๋ฒ ๋น๋ฉ (0) | 2021.03.18 |
BOJ 16397 - ํ์ถ (0) | 2021.03.18 |
BOJ 2563 - ์์ข ์ด (0) | 2021.03.18 |
๐ฌ ๋๊ธ