일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- lv4
- CodingTest
- 연습문제
- 코딩테스트
- 코테
- mysql
- 파이썬
- join
- BFS
- programmers
- 조합
- import re
- 시간복잡도
- 코딩
- 데이터분석
- Queue
- lambda
- coding test
- time complexity
- 완전탐색
- itertools
- collections
- python
- Level2
- counter
- Stack
- 프로그래머스
- coding
- level4
- sql
- Today
- Total
ror_coding
[Programmers] 게임 맵 최단거리 - 1844 본문
728x90
BFS 문제... queue를 이용해서 구현한다 !
어려웠지만 BFS를 배우기 매우 유용했던 문제 !!!
Question
게임 맵의 상태 maps가 매개변수로 주어질 때, 캐릭터가 상대 팀 진영에 도착하기 위해서 지나가야 하는 칸의 개수의 최솟값을 return 하도록 solution 함수를 완성해주세요. 단, 상대 팀 진영에 도착할 수 없을 때는 -1을 return 해주세요.
Point
(어떤 분께서 댓글로 DFS/BFS의 차이에 대해 야무진 설명을...)
- DFS : 성공이든 실패든 끝까지 한 경로만 조짐
- BFS : 여러 경로를 한 단계씩 검색 -> 짧은 경로가 가장 먼저 도달함
Code
from collections import deque
def solution(maps):
x, y = 1, 1
add = [0]*(len(maps[0]))
goal = [len(maps), len(maps[0])]
maps.insert(0,add)
for m in maps:
m.insert(0,0)
m.append(0)
maps.append(add)
maps[1][1] = 0
queue = deque()
dx = [0,1,0,-1] # 아래, 오, 위, 왼
dy = [1,0,-1,0]
queue.append((x,y,1))
while(queue):
x,y,cnt = queue.popleft()
if (x==goal[0] and y==goal[1]) :
return cnt
for xx, yy in zip(dx, dy):
nx = x+xx
ny = y+yy
if (maps[nx][ny] == 1):
maps[nx][ny] = 0
queue.append((nx,ny,cnt+1))
return -1
On my github
728x90
'Algorithm > Python' 카테고리의 다른 글
[Programmers] 더 맵게 - 42626 (0) | 2024.12.08 |
---|---|
[Python] Heap (Priority Queue) (1) | 2024.12.08 |
[Programmers] 뒤에 있는 큰 수 찾기 - 154539 (0) | 2024.12.07 |
[Programmers] 방문 길이 - 49994 (0) | 2024.12.07 |
[Programmers] [3차] n진수 게임 - 17687 (0) | 2024.12.07 |