华为笔试题:数独的填充
为什么我这样写会出现死循环呢?
package 华为笔试;
import java.util.ArrayList;
import java.util.Scanner;
public class 数独 {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int [][]array=new int[9][9];
ArrayList<int[]> list=new ArrayList<>();
while(sc.hasNext()){
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
array[i][j]=sc.nextInt();
if(array[i][j]==0){
int[]index=new int[2];
index[0]=i;
index[1]=j;
list.add(index);
}
}
}
dfs(0,array,list);
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
System.out.print(array[i][j]+" ");
}
System.out.println();
}
list=new ArrayList<>();
}
}
//num用来记录已经多少个0填充了数据
public static boolean dfs(int num,int [][]array,ArrayList<int[]> list){
if(num>=list.size()){
return true;
}
for(int[] arr:list){
int X=arr[0];
int Y=arr[1];
if(array[X][Y]==0){
for(int i=1;i<=9;i++){
if(canRun(X,Y,i,array)){
array[X][Y]=i;
if(dfs(num+1,array,list))
return true;
array[X][Y]=0;
}
}
}
}
return false;
}
public static boolean canRun(int row,int col,int c,int [][] array){
for (int i = 0; i < array.length; i++) {
if (array[i][col] == c)
return false;
if (array[row][i] == c)
return false;
}
int xBegin = (row / 3) * 3, yBegin = (col / 3) * 3;
for (int i = xBegin; i < xBegin + 3; i++) {
for (int j = yBegin; j < yBegin + 3; j++) {
if (array[i][j] == c)
return false;
}
}
return true;
}
}
测试用例:
0 9 5 0 2 0 0 6 0
0 0 7 1 0 3 9 0 2
6 0 0 0 0 5 3 0 4
0 4 0 0 1 0 6 0 7
5 0 0 2 0 7 0 0 9
7 0 3 0 9 0 0 2 0
0 0 9 8 0 0 0 0 6
8 0 6 3 0 2 1 0 5
0 5 0 0 7 0 2 8 3
对应输出应该为:
3 9 5 7 2 4 8 6 1
4 8 7 1 6 3 9 5 2
6 2 1 9 8 5 3 7 4
9 4 2 5 1 8 6 3 7
5 6 8 2 3 7 4 1 9
7 1 3 4 9 6 5 2 8
2 3 9 8 5 1 7 4 6
8 7 6 3 4 2 1 9 5
1 5 4 6 7 9 2 8 3
#华为#0 9 5 0 2 0 0 6 0
0 0 7 1 0 3 9 0 2
6 0 0 0 0 5 3 0 4
0 4 0 0 1 0 6 0 7
5 0 0 2 0 7 0 0 9
7 0 3 0 9 0 0 2 0
0 0 9 8 0 0 0 0 6
8 0 6 3 0 2 1 0 5
0 5 0 0 7 0 2 8 3
对应输出应该为:
3 9 5 7 2 4 8 6 1
4 8 7 1 6 3 9 5 2
6 2 1 9 8 5 3 7 4
9 4 2 5 1 8 6 3 7
5 6 8 2 3 7 4 1 9
7 1 3 4 9 6 5 2 8
2 3 9 8 5 1 7 4 6
8 7 6 3 4 2 1 9 5
1 5 4 6 7 9 2 8 3