数独-java版

求数独问题

依然利用图的深度优先搜索算法求解

直接上代码:

public class 数独 {

    public static void main(String[] args) {
        String[][] map = { 
            { "5", "3", " ", " ", "7", " ", " ", " ", " " },
            { "6", " ", " ", "1", "9", "5", " ", " ", " " },
            { " ", "9", "8", " ", " ", " ", " ", "6", " " },
            { "8", " ", " ", " ", "6", " ", " ", " ", "3" },
            { "4", " ", " ", "8", " ", "3", " ", " ", "1" },
            { "7", " ", " ", " ", "2", " ", " ", " ", "6" },
            { " ", "6", " ", " ", " ", " ", "2", "8", " " },
            { " ", " ", " ", "4", "1", "9", " ", " ", "5" },
            { " ", " ", " ", " ", "8", " ", " ", "7", "9"}};

        getResult(map);

        System.out.println("结果:");
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                System.out.print(map[i][j] + "  ");
                if (j == map.length - 1) {
                    System.out.println();
                }
            }
        }
    }

    private static boolean getResult(String[][] map) {
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map[i].length; j++) {
                if (map[i][j] == " ") {
                    for (int k = 1; k < 10; k++) {
                        map[i][j] = k + "";
                        if (isAvail(i, j, map) && getResult(map)) {
                            return true;
                        } else {
                            // 还原
                            map[i][j] = " ";
                        }
                    }
                    //当最后一个元素不满足时,剪枝!
                    return false;
                }
            }
        }
        return true;
    }

    private static boolean isAvail(int x, int y, String[][] map) {
        // 检查x行
        for (int j = 0; j < map.length; j++) {
            if (j != y && map[x][j].equals(map[x][y])) {
                return false;
            }
        }
        // 检查y列
        for (int i = 0; i < map.length; i++) {
            if (i != x && map[i][y].equals(map[x][y])) {
                return false;
            }
        }

        for (int i = 3 * (x / 3); i < 3 * (x / 3 + 1); i++) {
            for (int j = 3 * (y / 3); j < 3 * (y / 3 + 1); j++) {
                if ((i != x || j != y) && map[i][j].equals(map[x][y])) {
                    return false;
                }
            }
        }

        return true;
    }

}

结果:

5  3  4  6  7  8  9  1  2  
6  7  2  1  9  5  3  4  8  
1  9  8  3  4  2  5  6  7  
8  5  9  7  6  1  4  2  3  
4  2  6  8  5  3  7  9  1  
7  1  3  9  2  4  8  5  6  
9  6  1  5  3  7  2  8  4  
2  8  7  4  1  9  6  3  5  
3  4  5  2  8  6  1  7  9
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值