Leetcode - Sudoku Solver

My code:

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

reference:
https://discuss.leetcode.com/topic/11327/straight-forward-java-solution-using-backtracking/2

暴力解法。复杂度应该很高很高。
对于 ‘.’ 尝试 1-9 九种填法,看 sudo 是否有效。
如果无效,直接返回false
此处剪枝。
isValid 函数写的也比较高效。因为我只用判断这个点加入后,是否会使得sudoku变得无效。
所以只用判断他所在的行,所在的列,所在的九宫格,就行了。

Anyway, Good luck, Richardo! — 09/22/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/928695126e06#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞