๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/1844
ํ์ด
# ํ๋ก๊ทธ๋๋จธ์ค 2๋จ๊ฒ - ๊ฒ์ ๋งต ์ต๋จ๊ฑฐ๋ฆฌ
from collections import deque
def solution(maps):
n = len(maps)
m = len(maps[0])
visited = [[0]*m for _ in range(n)]
q = deque()
q.append((0,0))
dx, dy = [0,0,-1,1], [1,-1,0,0]
visited[0][0] = 1
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] == 1 and not visited[nx][ny]:
visited[nx][ny] = visited[x][y] + 1
q.append((nx, ny))
if visited[-1][-1]:
return visited[-1][-1]
else:
return -1
print(solution([[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]]))
print(solution([[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]]))
๊ธฐ๋ณธ์ ์ธ BFS ๋ฌธ์ ์ด๋ค. ๋ญ๊ฐ ๋ฌธ์ ์๋์ง ๋ชจ๋ฅด๊ฒ ๋๋ฐ ๊ณ์ ๋ฐํ์ ์๋ฌ๊ฐ ๋์ ํค๋ฉ์๋ค.
'๐๏ธ Algorithm > โฌ ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
โฌ [Programmers] [Java] [Level1] ์๋ฆฟ์ ๋ํ๊ธฐ (0) | 2023.12.11 |
---|---|
โฌ [Programmers] [Python] [Level3] ์ฌํ ๊ฒฝ๋ก (1) | 2023.05.10 |
โฌ [Programmers] [Python] [Level2] ์นด๋ ๋ญ์น (0) | 2023.04.17 |
โฌ [Programmers] [Python] [Level2] ๋ ๋งต๊ฒ (0) | 2023.04.17 |
โฌ [Programmers] [Python] [2018 KAKAO BLIND RECRUITMENT] [Level2] [3์ฐจ] n์ง์ ๊ฒ์ (0) | 2023.04.17 |