华为笔试题:数独的填充

为什么我这样写会出现死循环呢?


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
#华为#
全部评论
数独算法最明显的解法是使用回溯算法,这样不需要记录历史填充。同时为了提高运算速度,使用bool数组判断是否使用过
点赞 回复 分享
发布于 2022-04-24 17:55
我知道了 ,这里面少了一个关键的减枝,就是当一个节点当它取完1-9之后还不能返回true,则直接返回false!
点赞 回复 分享
发布于 2018-08-08 16:19
list应该是需要填充的位置吧。为什么每次dfs都从第一个开始?不应该填了一个,再填下一个嘛?
点赞 回复 分享
发布于 2018-08-06 23:10

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务