你一定听说过“数独”游戏。
如【图1.png】,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
数独的答案都是唯一的,所以,多个解也称为无解。
本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。
本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。
格式要求,输入9行,每行9个字符,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。
例如:
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700
程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764
再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400
程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452
资源约定:
峰值内存消耗(含虚拟机) < 256M
CPU消耗 < 2000ms
=====================
思路:
幻方问题->dfs
看一眼这个输入示例,感觉0听过的->搜索深度有点大->剪枝
public class Main{
static char[][] a =new char[9][9];
public static void main(String[] args) {
init();
dfs(0 ,0);
for(int i =0 ;i <9 ;i ++) {for(int j =0 ;j <9 ;j ++) System.out.print(a[i][j]); System.out.println();}
}
private static boolean dfs(int y, int x) {
//找到下一个坑
while(true) {
if(y ==9 &&x ==0) return true;
if(a[y][x] =='0') break;
if(++ x ==9) {y ++; x =0;}
}
for(char i ='1' ;i <='9' ;i ++) {
a[y][x] =i;
if(check(y ,x)) if(dfs(y ,x)) return true;
a[y][x] ='0';
}
return false;
}
private static boolean check(int y, int x) {
//行
for(int tmp_x =0 ;tmp_x <9 ;tmp_x ++) if(tmp_x !=x &&a[y][tmp_x] ==a[y][x]) return false;
//列
for(int tmp_y =0 ;tmp_y <9 ;tmp_y ++) if(tmp_y !=y &&a[tmp_y][x] ==a[y][x]) return false;
//九宫格
int sta_y =y /3 *3 ,sta_x =x /3 *3;
for(int tmp_y =sta_y ;tmp_y <sta_y +3 ;tmp_y ++)
for(int tmp_x =sta_x ;tmp_x <sta_x +3 ;tmp_x ++)
if(tmp_y !=y &&tmp_x !=x &&a[tmp_y][tmp_x] ==a[y][x]) return false;
return true;
}
private static void init() {
Scanner sc = new Scanner(System.in);
for(int i =0 ;i <a.length ;i ++) a[i] =sc.next().toCharArray();
sc.close();
}
}