JAVA解数独

版本一



import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Suduku3 {

    public static final Set<Integer> nums = Stream.iterate(1, n -> n + 1).limit(9).collect(Collectors.toSet());

    public static int round = 0;

    public static int[][] solve(int[][] sudo) {
        round++;
        if (check(sudo)) {
            return sudo;
        }
        Map<String, Object> map = find(sudo);
        Set<Integer> backs = (Set<Integer>) map.get("result");
        if (backs != null && backs.size() > 0) {
            for (Integer back : backs) {
                int[][] cpsudo = copy(sudo);
                int i = (int) map.get("i");
                int j = (int) map.get("j");
                cpsudo[i][j] = back;
                cpsudo = solve(cpsudo);
                if (check(cpsudo)) {
                    return cpsudo;
                }
            }

        }
        return sudo;
    }

    private static Map<String, Object> find(int[][] sudo) {
        Map<String, Object> map = new HashMap<>();
        Set<Integer> result = new HashSet<>(nums);
        for (int i = 0; i < sudo.length; i++) {
            for (int j = 0; j < sudo[i].length; j++) {
                if (sudo[i][j] == 0) {
                    Set<Integer> backs = new HashSet<>(nums);
                    for (int m = 0; m < sudo.length; m++) {
                        for (int n = 0; n < sudo[m].length; n++) {
                            if (sudo[m][n] > 0) {
                                if (m == i || n == j) {
                                    backs.remove(sudo[m][n]);
                                }
                                if (m / 3 == i / 3 && n / 3 == j / 3) {
                                    backs.remove(sudo[m][n]);
                                }

                            }
                        }
                    }
                    if (backs.size() < result.size()) {
                        result = new HashSet<>(backs);
                        map.put("i", i);
                        map.put("j", j);
                        map.put("result", result);
                    }
                }
            }
        }
        return map;
    }

    public static void print(int[][] sudo) {
        for (int[] ints : sudo) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }
        System.out.println("===============================================");
    }

    public static boolean check(int[][] sudo) {
        if (null == sudo) {
            return false;
        }
        for (int i = 0; i < sudo.length; i++) {
            for (int j = 0; j < sudo[i].length; j++) {
                if (sudo[i][j] == 0) {
                    return false;
                }
                int num = sudo[i][j];
                for (int m = 0; m < sudo.length; m++) {
                    for (int n = 0; n < sudo[m].length; n++) {
                        if (m == i && n == j) {
                            continue;
                        }
                        if (sudo[m][n] == num) {
                            if (m == i || n == j) {
                                return false;
                            }
                            if (m / 3 == i / 3 && n / 3 == j / 3) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
        return true;
    }

    public static int[][] copy(int[][] arrays) {
        int[][] result = new int[arrays.length][arrays[0].length];
        for (int i = 0; i < arrays.length; i++) {
            for (int j = 0; j < arrays[i].length; j++) {
                result[i][j] = arrays[i][j];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] sudo = new int[][]{
                {0, 0, 0, 0, 0, 3, 0, 0, 5},
                {8, 0, 0, 0, 0, 0, 0, 9, 0},
                {0, 5, 0, 2, 0, 0, 8, 0, 6},
                {0, 0, 0, 8, 2, 0, 0, 5, 9},
                {0, 0, 4, 0, 0, 0, 6, 0, 0},
                {2, 9, 0, 0, 3, 1, 0, 0, 0},
                {9, 0, 2, 0, 0, 8, 0, 4, 0},
                {0, 4, 0, 0, 0, 0, 0, 0, 7},
                {3, 0, 0, 1, 0, 0, 0, 0, 0}
        };
        Date start = new Date();
        sudo = solve(sudo);
        print(sudo);
        System.out.println(round);
        System.out.println(new Date().getTime() - start.getTime());
    }
}

版本二(减少递归调用)



import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Suduku2 {

    public static int round = 0;
    public static final Set<Integer> nums = Stream.iterate(1, n -> n + 1).limit(9).collect(Collectors.toSet());

    public static int[][] solve(int[][] sudo) {
        round++;
        if (check(sudo)) {
            return sudo;
        }
        int[][] cpsudo = copy(sudo);
        List<Map<String, Integer>> mapList = findOnlyOne(sudo);
        for (Map<String, Integer> objectMap : mapList) {
            int i = objectMap.get("i");
            int j = objectMap.get("j");
            int n = objectMap.get("result");
            cpsudo[i][j] = n;
            if (check(cpsudo)) {
                return cpsudo;
            }
        }
        Map<String, Object> map = find(sudo);
        Set<Integer> backs = (Set<Integer>) map.get("result");
        if (backs != null && backs.size() > 0) {
            for (Integer back : backs) {
                int[][] cp2 = copy(cpsudo);
                int i = (int) map.get("i");
                int j = (int) map.get("j");
                cp2[i][j] = back;
                cp2 = solve(cp2);
                if (check(cp2)) {
                    return cp2;
                }
            }

        }
        return cpsudo;
    }

    /**
     * 寻找唯一解
     *
     * @param sudo
     * @return
     */
    private static List<Map<String, Integer>> findOnlyOne(int[][] sudo) {
        List<Map<String, Integer>> list = new ArrayList<>();
        for (int i = 0; i < sudo.length; i++) {
            for (int j = 0; j < sudo[i].length; j++) {
                if (sudo[i][j] != 0) {
                    continue;
                }
                Set<Integer> backs = new HashSet<>(nums);
                for (int m = 0; m < sudo.length; m++) {
                    for (int n = 0; n < sudo[m].length; n++) {
                        if (sudo[m][n] == 0) {
                            continue;
                        }
                        if (m == i || n == j
                                || (m / 3 == i / 3 && n / 3 == j / 3)) {
                            backs.remove(sudo[m][n]);
                        }
                    }
                }
                if (backs.size() == 1) {//单元格有唯一解
                    Map<String, Integer> map = new HashMap<>();
                    map.put("i", i);
                    map.put("j", j);
                    map.put("result", backs.iterator().next());
                    sudo[i][j] = map.get("result");
                    list.add(map);
                }
            }
        }
        if (list.size() > 0) {//根据已知唯一解继续寻找
            list.addAll(findOnlyOne(sudo));
            return list;
        } else {//直到找不到
            return list;
        }
    }

    /**
     * 当没有唯一解时
     * 寻找解最少的单元格
     * @param sudo
     * @return
     */
    private static Map<String, Object> find(int[][] sudo) {
        Map<String, Object> map = new HashMap<>();
        Set<Integer> result = new HashSet<>(nums);
        for (int i = 0; i < sudo.length; i++) {
            for (int j = 0; j < sudo[i].length; j++) {
                if (sudo[i][j] != 0) {
                    continue;
                }
                Set<Integer> backs = new HashSet<>(nums);
                for (int m = 0; m < sudo.length; m++) {
                    for (int n = 0; n < sudo[m].length; n++) {
                        if (sudo[m][n] == 0) {
                            continue;
                        }
                        if (m == i || n == j
                                || (m / 3 == i / 3 && n / 3 == j / 3)) {
                            backs.remove(sudo[m][n]);
                        }
                    }
                }
                if (backs.size() < result.size()) {
                    result = new HashSet<>(backs);
                    map.put("i", i);
                    map.put("j", j);
                    map.put("result", result);
                }
            }
        }
        return map;
    }

    public static void print(int[][] sudo) {
        for (int[] ints : sudo) {
            for (int anInt : ints) {
                System.out.print(anInt + " ");
            }
            System.out.println();
        }
        System.out.println("===============================================");
    }

    /**
     * 检验数独是否完成
     * @param sudo
     * @return
     */
    public static boolean check(int[][] sudo) {
        if (null == sudo) {
            return false;
        }
        for (int i = 0; i < sudo.length; i++) {
            for (int j = 0; j < sudo[i].length; j++) {
                if (sudo[i][j] == 0) {
                    return false;
                }
                int num = sudo[i][j];
                for (int m = 0; m < sudo.length; m++) {
                    for (int n = 0; n < sudo[m].length; n++) {
                        if ((m == i && n == j) || sudo[m][n] != num) {
                            continue;
                        }
                        if (m == i || n == j
                                || (m / 3 == i / 3 && n / 3 == j / 3)) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    /**
     * 数组拷贝
     * @param arrays
     * @return
     */
    public static int[][] copy(int[][] arrays) {
        int[][] result = new int[arrays.length][arrays[0].length];
        for (int i = 0; i < arrays.length; i++) {
            for (int j = 0; j < arrays[i].length; j++) {
                result[i][j] = arrays[i][j];
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] sudo = new int[][]{
                {8, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 3, 6, 0, 0, 0, 0, 0},
                {0, 7, 0, 0, 9, 0, 2, 0, 0},
                {0, 5, 0, 0, 0, 7, 0, 0, 0},
                {0, 0, 0, 0, 4, 5, 7, 0, 0},
                {0, 0, 0, 1, 0, 0, 0, 3, 0},
                {0, 0, 1, 0, 0, 0, 0, 6, 8},
                {0, 0, 8, 5, 0, 0, 0, 1, 0},
                {0, 9, 0, 0, 0, 0, 4, 0, 0}
        };
        Date start = new Date();
        print(solve(sudo));
        System.out.println(round);
        Date parse1 = new Date();
        System.out.println(parse1.getTime() - start.getTime());
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python和Java都有一些压缩库可以用来压缩文件。对于Python,您可以使用zipfile模块,它提供了用于压缩zip文件的功能。下面是一个示例代码,演示了如何使用zipfile模块压缩zip文件: ```python import zipfile zip_file = "path/to/your/zip/file.zip" extract_dir = "path/to/extract/folder" with zipfile.ZipFile(zip_file, 'r') as zip_ref: zip_ref.extractall(extract_dir) ``` 对于Java,您可以使用java.util.zip包中的ZipInputStream类来压缩zip文件。下面是一个示例代码,演示了如何使用ZipInputStream压缩zip文件: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class UnzipExample { public static void main(String[] args) { String zipFile = "path/to/your/zip/file.zip"; String extractDir = "path/to/extract/folder"; try { byte[] buffer = new byte[1024]; File folder = new File(extractDir); if (!folder.exists()) { folder.mkdir(); } ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String fileName = zipEntry.getName(); File newFile = new File(extractDir + File.separator + fileName); new File(newFile.getParent()).mkdirs(); FileOutputStream fileOutputStream = new FileOutputStream(newFile); int length; while ((length = zipInputStream.read(buffer)) > 0) { fileOutputStream.write(buffer, 0, length); } fileOutputStream.close(); zipEntry = zipInputStream.getNextEntry(); } zipInputStream.closeEntry(); zipInputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值