数独:java版
下图是一个数独题,也是号称世界上最难的数独。当然了,对于计算机程序来说,只要算法是对的,难不难就不知道了,反正计算机又不累。回溯算法基本上就是穷举,解这种数独类的问题逻辑比较简单。
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400
import java.util.Scanner;
/**
* @ClassName: T6
* @description:回溯
* 数独
*
* @Author:Quin
* @Date:2020/9/2
**/
public class T6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] map = new int[9][9];
for (int i = 0; i < 9; i++) {
// 创建数独
String str = sc.next();
for (int j = 0; j < 9; j++) {
map[i][j] = str.charAt(j) - '0';
}
}
// 回溯解数独
Backtracking(map, 0);
sc.close();
}
private static void Backtracking(int[][] map, int index) {
if (index >= 81) {
// 函数出口
show(map);
return;
}
// 获取横纵坐标
int x = index / 9, y = index % 9;
if (map[x][y] == 0) {
for (int k = 1; k <= 9; k++) {
// 尝试
if (judgment(map, x, y, k)) {
map[x][y] = k;
Backtracking(map, index + 1);
}
map[x][y] = 0;
}
} else {
Backtracking(map, index + 1);
}
}
private static boolean judgment(int[][] map, int x, int y, int k) {
// 判断
for (int i = 0; i < 9; i++) {
// 判断横
if (map[x][i] == k) {
return false;
}
// 判断竖
if (map[i][y] == k) {
return false;
}
}
// 判断九宫格
int nx = x / 3 * 3, ny = y / 3 * 3;
for (int i = nx, X = nx + 3; i < X; i++) {
for (int j = ny, Y = ny + 3; j < Y; j++) {
if (map[i][j] == k) {
return false;
}
}
}
return true;
}
public static void show(int[][] map){
// 打印数独
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(map[i][j] + " ");
}
System.out.println();
}
}
}