-1 2 6 -1 -1 -1 -1 -1 -1
-1 -1 -1 5 -1 2 -1 -1 4
-1 -1 -1 1 -1 -1 -1 -1 7
-1 3 -1 -1 2 -1 1 8 -1
-1 -1 -1 3 -1 9 -1 -1 -1
-1 5 4 -1 1 -1 -1 7 -1
5 -1 -1 -1 -1 1 -1 -1 -1
6 -1 -1 9 -1 7 -1 -1 -1
-1 -1 -1 -1 -1 -1 7 5 -1
结果:2358
思路:对行列作dfs,循环数字,换行用’/‘和’%'来决定
import java.util.Scanner;
public class Main {
static int[][] map = new int[9][9];
static int c = 1;
public static boolean isVis(int n, int row, int col) {
for (int i=0;i<9;i++) {
if (n == map[row][i] || n == map[i][col])
return false;
}
for (int i = (row/3)*3;i<(row/3)*3+3;i++)
for (int j = (col/3)*3;j<(col/3)*3+3;j++)
if (map[i][j] == n)
return false;
return true;
}
public static void dfs(int row, int col) {
if (row == 9) {
System.out.println("----第"+c+"方法-----");
for (int i=0;i<9;i++) {
for (int j = 0;j<9;j++)
System.out.print(map[i][j]+" ");
System.out.println();
}
c++;
return;
}
if (map[row][col] == -1) {
for (int i = 1; i<=9; i++) {
if (isVis(i, row, col)) {
map[row][col] = i;
dfs(row + (col + 1)/9, (col + 1) %9);
}
}
map[row][col] = -1;
}else {
dfs(row + (col + 1)/9, (col + 1) %9);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i=0;i<9;i++)
for (int j = 0;j<9;j++)
map[i][j] = sc.nextInt();
dfs(0 ,0);
}
}