题目描述
你一定听说过“数独”游戏。
如图,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。
格式要求:
输入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位置都可能填1-9;采用深度遍历 找出一条合适的路径
代码
package lanqiao;
import java.util.Scanner;
public class 数独游戏 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
char[][] table = new char[9][9];
for(int i=0;i<9;i++)
table[i] = sc.nextLine().toCharArray();
dfs(table,0,0);
}
public static void dfs(char[][]table,int x,int y) {
if(x==9) {
print(table);
System.exit(0);
}
if(table[x][y]!='0')dfs(table,x+(y+1)/9,(y+1)%9);
else
{
for(int i=1;i<=9;i++)
{
if(check(table,x,y,i)) {
table[x][y] =(char)('0'+i);
dfs(table,x+(y+1)/9,(y+1)%9);
table[x][y]='0';
}
}
}
}
private static void print(char[][] table) {
for(int i =0;i<table.length;i++) {
for(int j = 0;j<table[0].length;j++) {
System.out.print(table[i][j]);
}
System.out.println();
}
}
public static boolean check(char[][] table,int x,int y,int m)
{
for(int i =0 ;i<9;i++) {
if(table[x][i]=='0'+m)return false;
}
for(int i =0 ;i<9;i++) {
if(table[i][y]=='0'+m)return false;
}
return true;
}
}
注意事项:
1.对每个格子的遍历dfs(table,x+(y+1)/9,(y+1)%9);
2.记得要回溯
3.对这种特殊输入要会处理 具体用到的技巧
char[][] table = new char[9][9];
for(int i=0;i<9;i++)
table[i] = sc.nextLine().toCharArray();
table[x][y] =(char)('0'+i);