【LeetCode】#37解数独(Sudoku Solver)

【LeetCode】#37解数独(Sudoku Solver)

题目描述

编写一个程序,通过已填充的空格来解决数独问题。
一个数独的解法需遵循如下规则:
1.数字 1-9 在每一行只能出现一次。
2.数字 1-9 在每一列只能出现一次。
3.数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
4.空白格用 ‘.’ 表示。

Description

Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
1.Each of the digits 1-9 must occur exactly once in each row.
2.Each of the digits 1-9 must occur exactly once in each column.
3.Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
4.Empty cells are indicated by the character ‘.’.

解法

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

猜你喜欢

转载自blog.csdn.net/weixin_43858604/article/details/84823277