CPU消耗 < 2000ms
import java.util.Scanner;
/**
*
*
* 数独游戏
*
测试数据1:
0 0 5 3 0 0 0 0 0
8 0 0 0 0 0 0 2 0
0 7 0 0 1 0 5 0 0
4 0 0 0 0 5 3 0 0
0 1 0 0 7 0 0 0 6
0 0 3 2 0 0 0 8 0
0 6 0 5 0 0 0 0 9
0 0 4 0 0 0 0 3 0
0 0 0 0 0 9 7 0 0
测试数据2:
8 0 0 0 0 0 0 0 0
0 0 3 6 0 0 0 0 0
0 7 0 0 9 0 2 0 0
0 5 0 0 0 7 0 0 0
0 0 0 0 4 5 7 0 0
0 0 0 1 0 0 0 3 0
0 0 1 0 0 0 0 6 8
0 0 8 5 0 0 0 1 0
0 9 0 0 0 0 4 0 0
*
*/
public class Main
{
public static boolean flag = false; // 标记是否已找到
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int arr[][] = new int [10][10];
for (int i = 1; i < arr.length; i++)
for (int j = 1; j < arr[i].length; j++)
arr[i][j] = sc.nextInt();
sc.close();
dfs(1, 1, arr);
}
private static void dfs(int x, int y, int[][] arr)
{
if (flag) return ;
if (x > 9)
{
output(arr); flag = true;
return ;
}
if (y > 9)
{
dfs(x+1, 1, arr);
}
else if (arr[x][y] != 0) dfs(x,y+1,arr);
else
{
for (int i = 1; i < 10; i++)
{
if (check(x, y, i, arr))
{
arr[x][y] = i;
dfs(x, y+1, arr);
arr[x][y] = 0;
}
}
}
}
private static boolean check(int x, int y, int num, int[][] arr)
{
// 检查x轴
for (int i = 1; i < 10; i++)
{
if (arr[x][i] == num) return false;
}
// 检查y轴
for (int i = 1; i < 10; i++)
{
if (arr[i][y] == num) return false;
}
// 检查九宫格
for (int i = (x-1)/3*3+1; i <= (x-1)/3*3+3; i++)
{
for (int j = (y-1)/3*3+1; j <= (y-1)/3*3+3; j++)
{
if (arr[i][j] == num) return false;
}
}
return true;
}
private static void output(int[][] arr)
{
for (int i = 1; i < arr.length; i++)
{
for (int j = 1; j < arr[i].length; j++)
{
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
原文地址:http://blog.csdn.net/first_sight/article/details/44131635