Skip to content

Commit 2eb9a48

Browse files
committed
[PGS] 게임 맵 최단거리 / Level 2 / 힌트사용 / 50분
1 parent 09f4cb2 commit 2eb9a48

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from collections import deque
2+
3+
def bfs(maps, x, y, n, m, visited):
4+
queue = deque()
5+
queue.append((x,y))
6+
7+
while queue:
8+
x, y = queue.popleft()
9+
10+
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # 좌,우,하,상
11+
nx, ny = x + dx, y + dy
12+
13+
# maps 범위 안에 있어야 하고, 벽이 아니어야 하고(값이 1이어야 하고), 아직 방문하지 않았다면 탐색
14+
if 0 <= nx < n and 0 <= ny < m and maps[nx][ny] == 1 and visited[nx][ny] == False:
15+
visited[nx][ny] = True
16+
queue.append((nx, ny))
17+
18+
maps[nx][ny] = maps[x][y] + 1 # 값을 +1
19+
20+
# 이때 우측 하단의 상,좌,우의 값이 0이면 경로가 이어질 수 없다.
21+
# 목적지에 도달하지 못할 경우엔 -1 반환
22+
if maps[n-1][m-1] == 1:
23+
return -1
24+
else: # 도달했을 경우 최단 거리 반환
25+
return maps[n-1][m-1]
26+
27+
def solution(maps):
28+
n, m = len(maps), len(maps[0]) # maps의 행과 열의 크기
29+
visited = [[False] * m for _ in range(n)] # 방문여부 리스트
30+
visited[0][0] = True # 시작 지점 방문 표시
31+
32+
# bfs 탐색 시작
33+
answer = bfs(maps, 0, 0, n, m, visited)
34+
return answer

0 commit comments

Comments
 (0)