알고리즘/프로그래머스 문제풀이

[프로그래머스] lv.2 숫자 변환하기 python 풀이

감자156 2023. 5. 19. 16:02
반응형

풀이

bfs로 풀이함

 

문제

https://school.programmers.co.kr/learn/courses/30/lessons/154538

 

bfs 개념

https://cccaaa.tistory.com/22

 

감자블로그

공부하고 삽질한 것 정리하는 블로그

cccaaa.tistory.com

 

코드

import collections

def solution(x, y, n):
    q = collections.deque()
    q.append((x,0))
    
    visited = [0 for _ in range(1000001)]
    visited[x] = 1
    
    while q:
        x, cnt = q.popleft()
        if x == y :
            return cnt
        
        for i in range(3):
            if i == 0:
                nx = x + n
            else:
                nx = x * (i + 1)
            
            nx = int(nx)
            if nx<=y and visited[nx] == 0:
                q.append((nx,cnt + 1))
                visited[nx] = 1
                
    return -1

 

반응형