BOJ 1107번 리모컨

|
package BOJ.BruteForce;

import java.util.*;

public class BOJ_1107 {
    
    static boolean[] broken = new boolean[10];

    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        for (int i = 0; i < m; i++) {
            int x = sc.nextInt();
            broken[x] = true;
        }
        int ans = n - 100;
        if (ans < 0) {
            ans = -ans;
        }
        for (int i = 0; i <= 1000000; i++) {
            int c = i;
            int len = possible(c); // 한 번에 갈 수 있으면 횟수 리턴. 못 가면 0을 리턴
            if (len > 0) {
                int press = c - n; // 한 번에 갈 수 있는 수 - n = 버튼을 눌러야하는 횟수
                if (press < 0) {
                    press = -press;
                }
                if (ans > len + press) { // 버튼을 눌러야 하는 횟수 + 한 번에 갈 수 있는 수
                    ans = len + press;
                }
            }
        }
        System.out.println(ans);
    }

    private static int possible(int c) {
        if (c == 0) {
            if (broken[0]) {
                return 0;
            } else {
                return 1;
            }
        }
        int len = 0;
        while (c > 0) {
            if (broken[c % 10]) { // 고장난 버튼 있는지 확인
                return 0;
            }
            len += 1;
            c /= 10; // 자리별로 확인
        }
        return len;
    }
}