9乘9数独

    xiaoxiao2022-07-03  129

    package dfs; import java.util.Arrays; import java.util.Scanner; public class 数独9乘9 { static int[][] A ; public static void main(String[] args) { A = new int[9][9]; Scanner sc = new Scanner(System.in); for (int i = 0; i < A.length; i++){ char[] B = sc.nextLine().toCharArray(); for (int j = 0; j < A[0].length; j++){ A[i][j] = B[j] - '0'; } } System.out.println(); dfs(A,0,0); } public static void dfs(int[][] A,int x,int y) { if(x == 9) { print(A); System.out.println(); return; } if(A[x][y] == 0) { for (int k = 1; k < 10; k++){ if(check(A,x,y,k)) { A[x][y] = k; dfs(A,x+(y+1)/9,(y+1)%9); A[x][y] = 0; } } }else { dfs(A,x+(y+1)/9,(y+1)%9); } } private static boolean check(int[][] A, int x, int y, int k){ for (int i = 0; i < A.length; i++){ if(A[x][i] == k) return false; if(A[i][y] == k) return false; } for (int i = (x/3)*3; i < (x/3+1)*3; i++){ for (int j = (y/3)*3; j < (y/3+1)*3; j++){ if(A[i][j] == k) return false; } } return true; } public static void print(int[][] A) { for (int i = 0; i < A.length; i++) { for (int j = 0; j < A[0].length; j++) { System.out.print(A[i][j]); } System.out.println(); } } }
    最新回复(0)