숫자 변환하기

JJW·2024년 12월 16일

코딩 테스트

목록 보기
22/23

문제


문제 풀이

using System;
using System.Collections.Generic;

public class Solution {
    public int solution(int x, int y, int n) 
    {
        // BFS를 위한 큐 초기화
        Queue<Tuple<int, int>> queue = new Queue<Tuple<int, int>>();
        queue.Enqueue(new Tuple<int, int>(x, 0)); // (현재 값, 연산 횟수)

        // 방문 여부를 체크하는 배열
        bool[] visited = new bool[y + 1];
        visited[x] = true;

        while (queue.Count > 0)
        {
            var current = queue.Dequeue();
            int value = current.Item1;
            int steps = current.Item2;

            // 목표 값에 도달하면 연산 횟수 반환
            if (value == y)
            {
                return steps;
            }

            // 가능한 연산을 모두 시도
            if (value + n <= y && !visited[value + n])
            {
                visited[value + n] = true;
                queue.Enqueue(new Tuple<int, int>(value + n, steps + 1));
            }

            if (value * 2 <= y && !visited[value * 2])
            {
                visited[value * 2] = true;
                queue.Enqueue(new Tuple<int, int>(value * 2, steps + 1));
            }

            if (value * 3 <= y && !visited[value * 3])
            {
                visited[value * 3] = true;
                queue.Enqueue(new Tuple<int, int>(value * 3, steps + 1));
            }
        }

        // 목표 값에 도달할 수 없으면 -1 반환
        return -1;
    }
}
profile
Unity 게임 개발자를 준비하는 취업준비생입니다..

0개의 댓글