DevYoon

[๋ฐฑ์ค€] 1261. ์•Œ๊ณ ์ŠคํŒŸ (Python) ๋ณธ๋ฌธ

PS/Baekjoon

[๋ฐฑ์ค€] 1261. ์•Œ๊ณ ์ŠคํŒŸ (Python)

gimewn 2022. 6. 3. 13:46

link ๐Ÿ”— https://www.acmicpc.net/problem/1261

 

1261๋ฒˆ: ์•Œ๊ณ ์ŠคํŒŸ

์ฒซ์งธ ์ค„์— ๋ฏธ๋กœ์˜ ํฌ๊ธฐ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฐ€๋กœ ํฌ๊ธฐ M, ์„ธ๋กœ ํฌ๊ธฐ N (1 ≤ N, M ≤ 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๋ฏธ๋กœ์˜ ์ƒํƒœ๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆซ์ž 0๊ณผ 1์ด ์ฃผ์–ด์ง„๋‹ค. 0์€ ๋นˆ ๋ฐฉ์„ ์˜๋ฏธํ•˜๊ณ , 1์€ ๋ฒฝ์„ ์˜๋ฏธ

www.acmicpc.net

 

๐Ÿ”ฅ BFS

๐Ÿ”ฅ visit ๋ฐฐ์—ด์— ๋ฒฝ์„ ๋ถ€์ˆœ ํšŸ์ˆ˜๋ฅผ ๊ธฐ๋กํ•˜๋ฉฐ BFS๋ฅผ ๋Œ๋ฆฐ๋‹ค.

๐Ÿ”ฅ ๋ฒฝ์„ ๋ถ€์ˆด์•ผ ํ•  ๊ฒฝ์šฐ +1, ๋ฒฝ์„ ๋ถ€์ˆ˜์ง€ ์•Š์•„๋„ ๋˜๋Š” ๊ฒฝ์šฐ ํ˜„์žฌ ์œ„์น˜์˜ ํšŸ์ˆ˜๋ฅผ ๊ทธ๋Œ€๋กœ ๊ฐ€์ ธ๊ฐ€๊ณ , appendleft๋กœ ๋งจ ์•ž์— ๋„ฃ์–ด์ค€๋‹ค.

 

from collections import deque

X, Y = map(int, input().split())

board = [list(map(int, input())) for _ in range(Y)]
visit = [[0]*X for _ in range(Y)]

def BFS():
    q = deque()
    q.append((0, 0))
    visit[0][0] = 1
    dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    while q:
        ny, nx = q.popleft()
        for i, j in dir:
            dy, dx = ny+i, nx+j
            if 0 <= dy < Y and 0 <= dx < X:
                if visit[dy][dx] == 0:
                    if board[dy][dx] == 0:
                        visit[dy][dx] = visit[ny][nx]
                        q.appendleft((dy, dx))
                    else:
                        visit[dy][dx] = visit[ny][nx]+1
                        q.append((dy, dx))

BFS()
print(visit[Y-1][X-1]-1)