Java backTracking solution


  • 0
    C

    public void solveSudoku(char[][] board) {
    solve(board, 0, 0);
    }

    private boolean solve(char[][] board, int row, int column) {
        if (column == 9 || row == 9) {
            return true;
        }
    
        //If haven't filled any number, loop from 1 to 9 to find a possible solution.
        //else it's already filled with one number and go to check next slot.
        if (board[row][column] == '.') {
            for (char j = '1'; j <= '9'; j++) {
                if (change(row, column, j, board)
                        && solve(board, row, column+1)
                            && solve(board, row+1, 0)) {
                    return true;
                }
                board[row][column] = '.';
            }
        } else {
            return solve(board, row, column+1);
        }
    
        return false;
    }
    
    private boolean change(int row, int column, char val, char[][] board) {
        //To check if val is used in row, column and sub-box
        for (int i = 0; i < 9; i++) {
            if (board[row][i] == val
                    || board[i][column] == val
                        || board[3*(row/3) + i/3][3*(column/3) + i%3] == val) {
                return false;
            }
        }
        board[row][column] = val;
        return true;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.