반응형
https://programmers.co.kr/learn/courses/30/lessons/67259
코딩테스트 연습 - 경주로 건설
[[0,0,0,0,0,0,0,1],[0,0,0,0,0,0,0,0],[0,0,0,0,0,1,0,0],[0,0,0,0,1,0,0,0],[0,0,0,1,0,0,0,1],[0,0,1,0,0,0,1,0],[0,1,0,0,0,1,0,0],[1,0,0,0,0,0,0,0]] 3800 [[0,0,1,0],[0,0,0,0],[0,1,0,1],[1,0,0,0]] 2100 [[0,0,0,0,0,0],[0,1,1,1,1,0],[0,0,1,0,0,0],[1,0,0,1,0,1],[
programmers.co.kr



bfs 기반 탐색 문제이면서, 경로의 최소비용을 체크하는 문제.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from collections import deque | |
def solution(board): | |
def bfs(start): | |
# table[y][x] = 해당 위치에 도달하는 최솟값. | |
table = [[math.inf for _ in range(len(board))] for _ in range(len(board))] | |
# 진행 방향. 위 - 0, 왼쪽 - 1, 아래 = 2, 오른쪽 = 3 | |
dirs = [(-1,0),(0,-1),(1,0),(0,1)] | |
queue = deque([start]) | |
# 처음 위치의 비용 = 0 | |
table[0][0] = 0 | |
while queue: | |
# y좌표, x좌표, 비용, 진행방향 | |
y, x, cost, head = queue.popleft() | |
for idx, (dy, dx) in enumerate(dirs): | |
ny, nx = y + dy, x + dx | |
# 진행방향과 다음 방향이 일치하면 + 100, 다르면 전환비용 500 + 진행비용 100 = 600 | |
n_cost = cost + 600 if idx != head else cost + 100 | |
# board[y][x] == 0 : 진행방향에 벽이 없음. table[ny][nx] > n_cost : 다음 좌표의 최솟값보다 진행방향 비용이 작을 경우 | |
if 0 <= ny < len(board) and 0 <= nx < len(board) and board[ny][nx] == 0 and table[ny][nx] > n_cost: | |
# table 좌표 업데이트. | |
table[ny][nx] = n_cost | |
queue.append((ny, nx, n_cost, idx)) | |
return table[-1][-1] | |
return min(bfs((0,0,0,2)), bfs((0,0,0,3))) |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 프로그래머스. 2020 카카오 recruit - 블록 이동하기 (Level 3) (0) | 2020.09.07 |
---|---|
[Python] 프로그래머스. 최적의 행렬 곱셈 (Level 4) (0) | 2020.09.03 |
[Python] 프로그래머스. 2020 카카오 인턴 - 수식 최대화 (Level 2) (0) | 2020.09.01 |
[Python] 프로그래머스. 2020 카카오 인턴 - 키패드 누르기 (Level 1) (0) | 2020.08.31 |
[Python] 프로그래머스. 2020 카카오 인턴 - 보석 쇼핑 (Level 3) (0) | 2020.08.28 |