37. 解数独_困难_矩阵

 

 dfs,主要记住结束递归要用return

class Solution {

    int judge(char [][]board,int iIndex,int jIndex,char s){
        int flag = 0;
        for(int j=0;j<9;j++){
            if(board[iIndex][j] == s && jIndex!=j) flag=1;
        }
        for(int i=0;i<9;i++){
            if(iIndex !=i && board[i][jIndex]==s) flag = 1;
        }
        for(int i=(iIndex-iIndex%3);i <(iIndex-iIndex%3+3);i++){
            for(int j=(jIndex-jIndex%3);j<(jIndex-jIndex%3+3);j++){
                if(i!=iIndex && jIndex!=j && board[i][j]==board[iIndex][jIndex]){
                    flag =1;
                    break;
                }
            }
        }
        return flag;
    }

    void f(int level,int num,char[][]board,char[][]result,int [][]array){

//        System.out.println("=================");
        if(level==num){
            for(int i=0;i<9;i++){
                for(int j=0;j<9;j++){
                    result[i][j] = board[i][j];
                }
            }
            return;
        }else{
            for(int i =0;i<9;i++){
                board[array[level][0]][array[level][1]] = (char)('1'+i);
                if(judge(board,array[level][0],array[level][1],board[array[level][0]][array[level][1]])==0){
                    f(level+1,num,board,result,array);
                }
                board[array[level][0]][array[level][1]] = '.';

            }

        }
    }
    public void solveSudoku(char[][] board) {
        int num = 0;

        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                if(board[i][j]=='.'){
                    num++;
                }
            }
        }
        int [][] array = new int[num][2];
        int index =0;
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                if(board[i][j]=='.'){
                    array[index][0] = i;
                    array[index++][1] = j;
                }
            }
        }
        char[][] result = new char[board.length][board.length];
        f(0,num,board,result,array);
        for(int i=0;i<9;i++){
            for(int j=0;j<9;j++){
                board[i][j] = result[i][j];
            }
        }
    }

}

 

posted @ 2021-09-29 23:13  你的雷哥  阅读(114)  评论(0编辑  收藏  举报