Note []: The Law of violence is indeed very slow. The example here uses the machine on hand to run an average of 30 s.
Wuzy in the garden translated a foreign article about how to solve the number of independence in the tutorial is much faster:
Http://www.cnblogs.com/emanonwzy/archive/2011/05/12/2044881.html#2096360
========================================================== ============================
public class ShuDuTest { private static int[][] matrix = new int[9][9]; private static void init(String[] args) throws Exception {// String s = "8..........36......7..9.2...5...7.......457.....1...3...1....68..85...1..9....4.."; String s = ".8..4....3......1........2...5...4.69..1..8..2...........3.9....6....5.....2....."; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int index = i * 9 + j; if (s.charAt(index) == '.') matrix[i][j] = 0; else matrix[i][j] = s.charAt(index) - '0'; } } } private static void print() throws Exception { System.out.println(); System.out.println(depth); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } System.out.println(); } private static boolean isOk(int x, int y) throws Exception { int n = matrix[x][y]; for (int i = 0; i < 9; i++) { if (i != x && matrix[i][y] == n) return false; if (i != y && matrix[x][i] == n) 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 (i != x && j != y && matrix[i][j] == n) return false; } } return true; } private static boolean isFinish() throws Exception { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (matrix[i][j] == 0) return false; } } return true; } private static long depth = 0; private static void find() throws Exception { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (matrix[i][j] != 0) continue; for (int k = 1; k <= 9; k++) { matrix[i][j] = k; if (isOk(i, j)) { if (isFinish()) print(); else find(); } } matrix[i][j] = 0; return; } } } public static void main(String[] args) throws Exception { init(args); print(); find(); }}