2020 카카오 인턴십: 경주로 건설 (프로그래머스)

2021. 2. 15. 16:05코딩테스트

728x90
반응형

programmers.co.kr/learn/courses/30/lessons/67259?language=python3

 

코딩테스트 연습 - 경주로 건설

[[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

2020 카카오 블라인드: 블록 이동하기를 프로그래머스에서 풀고

다른 사람의 풀이로 아주 멋진 코드를 보고 감동받아서 다시 풀어봤습니다.

yield가 왜 만들어졌는지 체험적으로 알것같은 기분입니다.

 

from queue import PriorityQueue as pq
def solution(board):
    SIZE = len(board)
    OPEN, WALL = range(2)
    START1 = (0, 0, 0, 0) #cost, x, y, d
    START2 = (0, 0, 0, 1)
    END_POINT = (SIZE-1, SIZE-1)
    DELTAS = ((0, 1), (1, 0), (0, -1), (-1, 0)) #0, 1, 2, 3
    
    q = pq()
    q.put(START1)
    q.put(START2)
    visited = set()
    visited.add(START1)
    visited.add(START2)
    
    def _is_in_range(x, y):
        return 0 <= x < SIZE and 0 <= y < SIZE
    
    def _is_open(x, y):
        return board[x][y] == OPEN
    
    def _is_ok(x, y):
        return _is_in_range(x, y) and _is_open(x, y)
    
    def _yield_moves(cost, x, y, d):
        for i in range(4):
            if abs(i-d) == 2:
                continue
            dx, dy = DELTAS[i]        
            nx, ny = x + dx, y + dy
            if _is_ok(nx, ny):
                if i == d:
                    yield (cost+100, nx, ny, i)
                else:
                    yield (cost+600, nx, ny, i)
                    
    while q.queue:
        cost, x, y, d = q.get()
        if (x, y) == END_POINT:
                return cost
        for next_road in _yield_moves(cost, x, y, d):
            if next_road not in visited:
                q.put(next_road)
                visited.add(next_road)
            
        
    return

 

카카오 인턴십 코딩테스트 경주로 건설 프로그래머스 kakao blind 카카오코테 python 파이썬풀이