package innerclasses;
import java.util.Stack;
public class Sudo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// int[][] question = {
// { 7, 1, 2, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 4, 0, 0, 6, 0, 0 },
// { 0, 0, 0, 5, 0, 0, 0, 1, 9 },
// { 9, 4, 8, 7, 6, 2, 5, 3, 0 },
// { 0, 2, 6, 3, 9, 1, 7, 4, 0 },
// { 1, 7, 3, 8, 0, 0, 0, 0, 0 },
// { 2, 5, 7, 0, 0, 9, 8, 0, 0 },
// { 4, 3, 9, 6, 8, 0, 1, 2, 7 },
// { 6, 8, 0, 0, 0, 3, 0, 5, 4 }
// };
// int[][] question = { { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
// { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };
int[][] question = { { 6, 0, 4, 1, 0, 8, 2, 0, 9 },
{ 0, 2, 0, 0, 4, 0, 0, 0, 0 }, { 0, 0, 0, 2, 0, 5, 0, 0, 0 },
{ 0, 3, 0, 9, 0, 0, 0, 1, 0 }, { 9, 0, 6, 0, 0, 0, 4, 0, 7 },
{ 0, 0, 0, 0, 0, 4, 0, 3, 0 }, { 1, 0, 7, 4, 0, 9, 8, 0, 3 },
{ 0, 0, 0, 7, 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 6, 0, 0, 4, 0 }, };
int[][] answer = dosudo(question);
if (answer == null) {
System.out.print("no answer ");
} else {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(answer[i][j] + " ");
}
System.out.println();
}
}
}
public static int[][] dosudo(int[][] question) {
int[][] answer = new int[9][9];
Location currentLocation = new Location(-1, -1);
Stack<Location> locationStack = new Stack<Location>();
if (question == null || question.length != 9) {
return null;
}
for (int i = 0; i < 9; i++) {
System.arraycopy(question[i], 0, answer[i], 0, 9);
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (question[i][j] != 0)
continue;
int num = answer[i][j] + 1;
for (; num <= 9; num++) {
if (isOK(i, j, num, answer)) {
answer[i][j] = num;
locationStack.push(new Location(i, j));
break;
}
}
if (num == 10) {
answer[i][j] = 0;
try {
currentLocation = locationStack.pop();
i = currentLocation.m;
j = currentLocation.n;
j--;
} catch (Exception e) {
return null;
}
}
}
}
return answer;
}
public static boolean isOK(int m, int n, int num, int[][] tobe) {
int a = m / 3 * 3;
int b = n / 3 * 3;
for (int i = 0; i < 9; i++) {
if (tobe[m][i] == num || tobe[i][n] == num) {
return false;
}
}
for (int i = a; i < a + 3; i++) {
for (int j = b; j < b + 3; j++) {
if (tobe[i][j] == num) {
return false;
}
}
}
return true;
}
}
class Location {
int m;
int n;
Location(int m, int n) {
this.m = m;
this.n = n;
}
}
数独.java
最新推荐文章于 2023-02-13 20:29:44 发布