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

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Level 4 - ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

by HandHand 2021. 3. 1.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

BFS ๋ฅผ ํ†ตํ•ด ๋ชฉํ‘œ์ง€์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

๋ฐฉ๋ฌธ์—ฌ๋ถ€์™€ ๊ฑฐ๋ฆฌ ์ •๋ณด๋ฅผ ์ €์žฅํžˆ๊ธฐ ์œ„ํ•ด์„œ ๋”•์…”๋„ˆ๋ฆฌ ์ž๋ฃŒํ˜•์„ ์‚ฌ์šฉํ• ์ˆ˜๋„ ์žˆ์ง€๋งŒ ๊ฒŒ์ž„๋งต๊ณผ ๋™์ผํ•œ ์ด์ฐจ์› ๋ฐฐ์—ด์„ ์„ ์–ธํ•ด์„œ

-1์ผ ๊ฒฝ์šฐ๋Š” ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ง€์ , ๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ๋Š” ์ด๋ฏธ ๋ฐฉ๋ฌธํ•ด์„œ ์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•œ ์ง€์ ์œผ๋กœ ํŒ๋‹จํ•˜๋„๋ก ํ–ˆ๋‹ค.

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํŠธ๋ฆฌ ํƒ์ƒ‰์‹œ๊ฐ„์„ ์ ˆ์•ฝํ•  ์ˆ˜ ์žˆ์–ด์„œ ๋” ๋น ๋ฅธ ์ˆ˜ํ–‰์‹œ๊ฐ„์„ ๊ฐ€์ง€๊ฒŒ ๋œ๋‹ค.

์ฝ”๋“œ


from collections import deque


dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]


def bfs(maps, start):
    N, M = len(maps), len(maps[0])
    q = deque()

    dist = [[-1 for _ in range(M)] for _ in range(N)]
    goal = (N-1, M-1)

    q.append(start)
    dist[start[0]][start[1]] = 1

    while q:
        here = q.popleft()
        if here[0] == goal[0] and here[1] == goal[1]:
            return dist[here[0]][here[1]]

        for i in range(4):
            next_x, next_y = here[0] + dx[i], here[1] + dy[i]
            if 0 <= next_x < N and 0 <= next_y < M:
                if maps[next_x][next_y] != 0 and dist[next_x][next_y] == -1:
                    dist[next_x][next_y] = dist[here[0]][here[1]] + 1
                    q.append((next_x, next_y))
    return -1


def solution(maps):
    answer = bfs(maps, (0, 0))
    return answer


maps = [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]]
print(solution(maps))
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€