37.Sudoku Solver

36.Valid Sudoku

https://leetcode.com/problems/sudoku-solver/discuss/15752

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;
    }
    public boolean isValid(char[][] board, int row, int col, char c){
        int blockRow = (row / 3) * 3;
        int blockCol = (col / 3) * 3;
        for(int i = 0; i < board.length; i++){
            if(board[i][col] == c)
                return false;
            if(board[row][i] == c)
                return false;
            if(board[blockRow + i / 3][blockCol + i % 3] == c)
                return false;
        }
        return true;
    }
}

results matching ""

    No results matching ""