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.

Solution: 注意要backtracking,每次试完一个数要重置为'.'. 同一个九宫格里的坐标关系:board[3 * (row / 3) + i / 3][3 * (column / 3) + i % 3]

    public void solveSudoku(char[][] board) {
        if (board == null || board.length < 9 || board[0] == null || board[0].length < 9) {
            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] != '.') {
                    continue;
                }
                for (char k = '1'; k <= '9'; k++) {
                    if (isValid(board, i, j, k)) {
                        board[i][j] = k;
                        if(solve(board)){
                            return true;
                        }
                        board[i][j] = '.';
                    }
                }
                return false;
            }
        }
        return true;
    }
    private boolean isValid(char[][] board, int row, int column, char c) {
        for (int i = 0; i < 9; i++) {
            if(board[i][column] == c || board[row][i] == c || board[3 * (row / 3) + i / 3][3 * (column / 3) + i % 3] == c) {
                return false;
            }
        }
        return true;
    }

results matching ""

    No results matching ""