DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ (Python)

gimewn 2022. 11. 3. 01:49

link ๐Ÿ”— https://school.programmers.co.kr/learn/courses/30/lessons/1844

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ’ฌ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— BFS๋กœ ํ’€์—ˆ๋‹ค!

๐Ÿ’ฌ ๊ธฐ๋ณธ์ ์ธ BFS ๋ฌธ์ œ!

 

from collections import deque

dir = [(-1, 0), (1, 0), (0, -1), (0, 1)]

def BFS(Y, X, map):
    q = deque()
    q.append((0, 0, 0)) # y, x, cnt
    check = [[0]*X for _ in range(Y)]
    check[0][0] = 1
    while q:
        ny, nx, ncnt = q.popleft()

        if ny == Y-1 and nx == X-1:
            return ncnt+1

        for i, j in dir:
            dy, dx = ny+i, nx+j
            if 0 <= dy < Y and 0 <= dx < X:
                if check[dy][dx]:continue
                if map[dy][dx] == 0: continue
                check[dy][dx] = 1
                q.append((dy, dx, ncnt+1))
    return -1
    
def solution(maps):
    answer = 0
    Y = len(maps)
    X = len(maps[0])

    answer = BFS(Y, X, maps)
    return answer