๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 2178 - ๋ฏธ๋กœ ํƒ์ƒ‰

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 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

๐Ÿ’ฌ ๋Œ“๊ธ€