Wednesday, January 7, 2015

LeetCode 37: Sudoku Solver

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.


A sudoku puzzle...


...and its solution numbers marked in red.
public class Solution {
    private boolean isOver; // If have already found the solution or not
    
    public void solveSudoku(char[][] board) {
        // Backtracking problem
        if (board==null || board.length!=9 || board[0].length!=9)
            return;
        
        isOver = false;
        
        backTracking(board, 0, 0);
    }
    
    private void backTracking(char[][] board, int i, int j)
    {
        if (isOver)
            return;
            
        // Filling is over.    
        if (i == 9)
        {
            isOver = true;
            return;
        }
            
        // Turn to next row
        if (j == 9)
        {
            backTracking(board, i+1, 0);
            return;
        }

        if (board[i][j] == '.')
        {
            for (int k = 1; k <= 9; k++)
                if (isValid(board, i, j, (char)(k+'0')))
                {
                    board[i][j] = (char)(k+'0');
                    backTracking(board, i, j+1);
                    
                    // Note: Avoid erasing the correct solution.
                    if (!isOver)
                        board[i][j] = '.';
                }
        }
        else
            backTracking(board, i, j+1);
    }
    
    // Verify if it is valid Sudoku or not.
    private boolean isValid(char[][] board, int i, int j, char c)
    {
        // Check row
        for (int k = 0; k < 9; k++)
            if (board[i][k] == c)
                return false;
                
        // Check column
        for (int k = 0; k < 9; k++)
            if (board[k][j] == c)
                return false;
                
        // Check block
        for (int k = i/3*3; k < i/3*3+3; k++)
            for (int l = j/3*3; l < j/3*3+3; l++)
                if (board[k][l] == c)
                    return false;
                    
        return true;
    }
}

No comments:

Post a Comment