题解 | 24点游戏算法

24点游戏算法

https://www.nowcoder.com/practice/fbc417f314f745b1978fc751a54ac8cb

基于DFS算法,并考虑了括号特殊情况(即count == 2时的情况),详见代码:

import java.io.*;
import java.util.*;

/*
    知识点:递归、深度优先搜索、回溯算法
*/
public class Main {

    static int[] nums = new int[4];
    static int[] visit = new int[4];
    static int count = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        while ((str = br.readLine()) != null) {
            String[] numstr = str.split(" ");
            for (int i = 0; i < 4; i++) {
                nums[i] = Integer.parseInt(numstr[i]); // 读取数字
            }
            System.out.println(dfs(0));
        }
    }

    public static boolean dfs(int temp) {
        for (int i = 0; i < nums.length; i++) {
            if (visit[i] == 0) { // 如果是未使用的数字
                if (count++ == 2) {
                    int a = 0, b = 0;
                    for (int j = 0; j < 4; j++) {
                        if (visit[j] == 0) {
                            if (a == 0) {
                                a = nums[j];
                            } else {
                                b = nums[j];
                            }
                        }
                    }
                    for (double n : getAnyRes(a, b)) {
                        for (double m : getAnyRes(temp, n)) {
                            if (m == 24) {
                                return true;
                            }
                        }
                    }
                }
                visit[i] = 1; // 标记为已使用
                if (dfs(temp + nums[i]) // 递归判断
                        || dfs(temp - nums[i])
                        || dfs(temp * nums[i])
                        || (temp % nums[i] == 0 && dfs(temp / nums[i]))) {
                    // 如果存在满足条件的,终止循环
                    return true;
                }
                // 不存在满足条件的,说明当前的数字顺序不符要求,进行回溯,把标记重置为0
                visit[i] = 0;
                count--;
            }
        }
        // 数字都已使用且结果为24,返回真
        if (temp == 24) {
            return true;
        }
        // 不存在24,返回假
        return false;
    }

    private static List<Double> getAnyRes(double a, double b) {
        List<Double> res = new ArrayList<Double>();
        res.add(a + b);
        res.add(a * b);
        res.add(a - b);
        res.add(b - a);
        if (a != 0) {
            res.add(b / a);
        }
        if (b != 0) {
            res.add(a / b);
        }
        return res;
    }
}

全部评论

相关推荐

那一天的Java_Java起来:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
05-30 12:03
山西大学 C++
offer来了我跪着接:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务