数独

你一定听说过“数独”游戏。
如【图1.png】,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。

数独的答案都是唯一的,所以,多个解也称为无解。

本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。

本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。

格式要求,输入9行,每行9个字符,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。

例如:
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700

程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764

再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400

程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452

import java.util.Scanner;

public class Main {
    static int[][] a = new int[9][9];
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for(int i = 0; i < a.length; i ++) {
            String[] str = sc.nextLine().split("");
            for(int j = 0; j < a.length; j ++) {
                a[i][j] = Integer.parseInt(str[j]);
            }
        }
        dfs(0);
        for(int i = 0; i < a.length; i ++) {
            for(int j = 0; j < a.length; j ++) {
                if(j == a.length - 1) {
                    System.out.print(a[i][j]);
                    System.out.println();
                }
                else {
                    System.out.print(a[i][j]);
                }
            }
        }
    }
    public static boolean dfs(int step) {
        if(step >= 81) return true;
        int x = step / 9;
        int y = step % 9;
        if(a[x][y] == 0) {
            for(int i = 1; i <= 9; i ++) {
                a[x][y] = i;
                if(row_column(x, y, i) && judge(x, y, i)) {
                    if(dfs(step + 1))
                        return true;
                }
                a[x][y] = 0;
            }
        }
        else 
            return dfs(step + 1);
        return false;
    }
    private static boolean row_column(int x, int y, int n) {
        for(int i = 0; i < 9; i ++) {
            if(a[x][i] == n && i != y) return false;
            if(a[i][y] == n && i != x) return false;
        }
        return true;
    }
    private static boolean judge(int x, int y, int n) {
        int xx = x / 3;
        int yy = y / 3;
        
        for(int i = xx * 3; i < xx * 3 + 3; i ++) {
            for(int j = yy * 3; j < yy * 3 + 3; j ++) {
                if(a[i][j] == n) {
                    if(i == x && j == y) continue;
                    else return false;
                }
                    
            }
        }
        
        return true;
    }
}
原文地址:https://www.cnblogs.com/jizhidexiaobai/p/8570179.html