[BOJ][C#] 1107 리모컨

LimJaeJun·2024년 1월 2일
0

PS/BOJ

목록 보기
85/108

📕 문제

📌 링크

📗 접근 방식

고장난 버튼 표시:

  • 고장난 버튼을 표시하는 배열을 만들어둔다.

숫자 버튼만을 사용하여 이동:

  • 주어진 채널로 이동하는 데 필요한 최소 횟수를 계산한다.
  • 현재 채널과 주어진 채널 간의 차이(Math.Abs(n - curChannel))에 현재 채널에서 주어진 채널로 바로 이동하는 데 필요한 버튼 누름 횟수를 더한다.

고장난 버튼을 사용하지 않고 이동:

  • 0부터 1,000,000까지의 모든 채널에 대해 해당 채널이 고장나지 않은 버튼으로만 이루어져 있으면, 주어진 채널로 이동하는 데 필요한 버튼 누름 횟수를 계산하고 최소값을 업데이트한다.

결과 출력:

  • 최소 횟수를 출력한다.

📘 코드

namespace BOJ
{    
    class No_1107
    {
        static void Main()
        {
            int curChannel = 100;
            int n = InputInt();
            
            int m =  InputInt();
            // 고장난 버튼이 없을 경우
            // 타겟채널의 길이와 현재 채널의 차이 중 작은 것을 출력
            if (m == 0)
            {
                Console.WriteLine($"{Math.Min(n.ToString().Length, Math.Abs(n - curChannel))}");

                return;
            }

            List<int> buttonList = new List<int>() { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            var errorButtons = InputArray();
            
            // 타겟채널이 현재채널일 경우
            // 0을 출력
            if (n == curChannel)
            {
                Console.WriteLine("0");

                return;
            }
            
            for (int i = 0; i < m; i++)
            {
                buttonList[errorButtons[i]] = 1;
            }

            int minPressCount = GetMinPressCount(n, curChannel, buttonList);

            Console.WriteLine(minPressCount);
        }

        static int GetMinPressCount(int n, int curChannel, List<int> buttonList)
        {
            int minPressCount = Math.Abs(n - curChannel);

            for (int i = 0; i <= 1_000_000; i++)
            {
                if (IsNotErrorButton(i, buttonList) == false) continue;

                int pressCount = Math.Abs(n - i) + i.ToString().Length;
                minPressCount = Math.Min(pressCount, minPressCount);
            }

            return minPressCount;
        }

        static bool IsNotErrorButton(int channel, List<int> buttonList) => channel.ToString().All(t => buttonList[t - '0'] != 1);
        static int InputInt() => int.Parse(Console.ReadLine());
        static int[] InputArray() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
    }
}

📙 오답노트

GetMinPressCount함수에서 반복문의 범위를 채널의 범위인 0부터 500_000까지 탐색하였었는데 당연하게 예제입력에서 오류가 있었고 높은 곳에선 내려오는 경우와 채널은 무한히 존재하는 이유때문에 500_000까지가 아닌 1_000_000까지 탐색하였다.

📒 알고리즘 분류

  • 브루트포스 알고리즘
profile
Dreams Come True

0개의 댓글

관련 채용 정보