芬蘭數學家因卡拉花費3個月設計出了世界上迄今難度最大的數獨游戲,而且它只有一個答案。因卡拉說只有思考能力最快、頭腦最聰明的人才能破解這個游戲。
今日,一則騰訊的新聞稱中國老頭三天破解世界最難九宮格,雖然最后老人是改了一個數字,但是引起本人一時興趣,想通過計算機程序求解該問題,于是在宿舍呆了一下午,終于成功求解,程序源碼如下。
public class Point {
private int col;// 行號
private int row;// 列號
private boolean flag;// 真為未設置。
private int value;
// 構造點
public Point(int col, int row, boolean flag, int value) {
super();
this.col = col;
this.row = row;
this.flag = flag;
this.value = value;
}
public void changeFlag() {
flag = !flag;
}
public boolean getFlag() {
return flag;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public boolean canHere(Point[][] pArr) {
boolean cb = canCol(pArr);
boolean cr = canRow(pArr);
boolean cminiArr = canMiniArr(pArr);
return cb && cr && cminiArr;
}
//判斷在小3*3格子里是否有相同元素
private boolean canMiniArr(Point[][] pArr) {
int coltemp = this.col % 3;
int rowtemp = this.row % 3;
for (int i = this.col - coltemp; i < col + (3 - coltemp); i++) {
for (int j = this.row - rowtemp; j < row + (3 - rowtemp); j++) {
if(i == this.col && j == this.row){
continue;
}else{
if(this.value == pArr[i][j].getValue()){
return false;
}
}
}
}
return true;
}
// 判斷列上是否有相同元素
private boolean canRow(Point[][] pArr) {
for (int i = 0; i < 9; i++) {
if (i == this.col) {
continue;
} else {
if (this.value == pArr[i][this.row].value) {// 行變,列不變
return false;
}
}
}
return true;
}
// 判斷行上是否有相同元素
private boolean canCol(Point[][] pArr) {
for (int i = 0; i < 9; i++) {
if (i == this.row) {
continue;
} else {
if (this.value == pArr[this.col][i].value) {// 列邊,行不變
return false;
}
}
}
return true;
}
}