【2048的最少次数】

这篇文章介绍了如何使用Java编程语言,通过递归和迭代的方式解决Test2048问题,计算一维数组中元素合并成2所需的最少操作次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Scanner;

public class Test2048 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int times = scan.nextInt();
        int[][] arr = new int[times][10];
        for (int i = 0; i < times; i++) {
            for (int j = 0; j < 10; j++) {
                arr[i][j] = scan.nextInt();
            }
        }

        for (int i = 0; i < times; i++) {
            System.out.println(leastCount(arr[i], 0));
        }
    }

    // 递归寻找一维数组的最少的合成次数
    public static int leastCount(int[] arr, int count) {
        if (arr[9] >= 2) {
            return count;
        }
        
        int index = 8;
        while (index >= 0 && arr[index] < 2) {
            index--;
        }
        arr[index] -= 2;
        arr[index + 1] += 1;
        
        return leastCount(arr, count + 1);
    }
}
 

import java.util.Scanner;

public class Test2048 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int times = scan.nextInt();
        int[][] arr = new int[times][10];
        for (int i = 0; i < times; i++) {
            for (int j = 0; j < 10; j++) {
                arr[i][j] = scan.nextInt();
            }
        }

        for (int i = 0; i < times; i++) {
            System.out.println(leastCount(arr[i]));
        }
    }

    // 迭代寻找一维数组的最少的合成次数
    public static int leastCount(int[] arr) {
        int count = 0;
        while (arr[9] < 2) {
            int index = 8;
            while (index >= 0 && arr[index] < 2) {
                index--;
            }
            if (index >= 0) {
                arr[index] -= 2;
                arr[index + 1] += 1;
                count++;
            } else {
                break;
            }
        }
        return count;
    }
}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值