[LeetCode]Sudoku Solver

单纯的dfs,感觉应该有更好的办法

public class Solution {
    public void solveSudoku(char[][] board) {
        helper(board);
    }
    public boolean helper(char[][] board) {
        boolean flg = true;
        for (int r = 0; r < 9; r++) {
            for (int c = 0; c < 9; c++) {
                if (board[r][c] == '.') {
                    flg = false;
                    boolean[] tmp = new boolean[9];
                    for (int i = 0; i < 9; i++) {
                        if (board[i][c] != '.') {
                            tmp[(int)board[i][c] - '1'] = true;
                        }
                        if (board[r][i] != '.') {
                            tmp[(int)board[r][i] - '1'] = true;
                        }
                    }
                    for (int i = (r / 3) * 3; i < (r / 3) * 3 + 3; i++) {
                        for (int j = (c / 3) * 3; j < (c / 3) * 3 + 3; j++) {
                            if (board[i][j] != '.') {
                                tmp[(int)board[i][j] - '1'] = true;
                            }
                        }
                    }
                    for (int i = 1; i <= 9; i++) {
                        if (!tmp[i - 1]) {
                            board[r][c] = (char)(i + '0');
                            if (helper(board)) {
                                return true;
                            }
                        }
                    }
                    board[r][c] = '.';
                    return false;
                }
            }
        }
        return flg;
    }
}

 

posted @ 2015-12-02 14:26  Weizheng_Love_Coding  阅读(140)  评论(0编辑  收藏  举报