美文网首页ACM题库~
LeetCode 37. Sudoku Solver

LeetCode 37. Sudoku Solver

作者: 关玮琳linSir | 来源:发表于2017-09-15 16:10 被阅读55次

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'

You may assume that there will be only one unique solution.

A sudoku puzzle...

...and its solution numbers marked in red.

题意:求解一个数独,的完整解。

public void solveSudoku(char[][] board) {
        solve(board);
    }
    private boolean solve(char[][] board){
         for(int row = 0;row<9;row++){
             for(int col = 0;col<9;col++){
                 if(board[row][col] ==  '.'){
                     for(char i = '1';i<='9';i++){
                         board[row][col] = i;
                         if(isValid(board,row,col) && solve(board))
                            return true;
                         board[row][col] = '.';
                     }
                     return false;
                 }
             }
         }
         return true;
    }
    private boolean isValid(char[][] board,int row,int col){
        for(int i = 0;i<9;i++){
            if(i!=col && board[row][i] == board[row][col])
                return false;
        }
        for(int i = 0;i<9;i++){
            if(i!=row && board[i][col] == board[row][col])
                return false;
        }
        int beginRow = 3*(row/3);
        int beginCol = 3*(col/3);
        for(int i = beginRow;i<beginRow+3;i++){
            for(int j = beginCol;j<beginCol+3;j++){
                if(i!=row && j!=col && board[i][j] == board[row][col])
                    return false;
            }
        }
        return true;
    }

相关文章

网友评论

    本文标题:LeetCode 37. Sudoku Solver

    本文链接:https://www.haomeiwen.com/subject/zgossxtx.html