求x到y的最少计算次数

不太清楚为什么会是BFS和DFS

哦,这样,从x出发,每次“+1”、“-1”、“*2”三条路径

广度优先,一层一层往下走,同时一层一层向下构造,得到第一个等于y的,层数就是结果

    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);
        String[] s = scanner.next().split(",");
        int x = Integer.parseInt(s[0]);
        int y = Integer.parseInt(s[1]);
        Queue<Integer> que = new ArrayDeque<>();
        int level = -1, size;
        que.add(x);
        while (!que.isEmpty()) {
            level++;
            size = que.size();
            for (int i = 0; i < size; i++) {
                int temp = que.peek();
                que.remove();
                if (temp == y) {
                    que.clear();
                    break;
                }
                if (temp + 1 <= 100) que.add(temp + 1);
                if (temp - 1 >= -100) que.add(temp - 1);
                if (2 * temp >= -100 && 2 * temp <= 100) que.add(2 * temp);
            }
        }
        System.out.println(level);
    }

就是不喜欢用Java做题,怎么看都不优雅

但是我尝试-100,100这个测试用例的时候就直接OOM了

考虑动态规划?

posted @ 2022-12-18 13:17  YaosGHC  阅读(62)  评论(0)    收藏  举报