Tuesday, April 12, 2016

[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...
1. Many troubles, should have a better solution.
public class Solution {
    
    private boolean solveSodukuAtPos(char[][] board, int i, int j){
        
        if(9 == i)
            return true;
        
        if('.' != board[i][j])
            return solveSodukuAtPos(board, j == 8? i+1:i, j == 8? 0:j+1); 
        
        int[] arr = new int[10];
        for(int k = 0; k < 9; ++k){
            if('.' != board[i][k]){
                int v = Character.getNumericValue(board[i][k]);
                
                arr[v] = 1;
            }
        }
        for(int k = 0; k < 9; ++k){
            if('.' != board[k][j]){
                int v = Character.getNumericValue(board[k][j]);
                arr[v] = 1;
            }
        }
        int x = i / 3 * 3;
        int y = j / 3 * 3;
        for(int m = 0; m < 3; ++m)
        for(int n = 0; n < 3; ++n){
            if('.' != board[x+m][y+n]){
                int v = Character.getNumericValue(board[x+m][y+n]);
                arr[v] = 1;
            }
        }
        
        for(int k = 1; k < 10; ++k){
            if(0 == arr[k]){
                // Java is not good at parsing, converting ..
                board[i][j] = Integer.toString(k).charAt(0);
                if(true == solveSodukuAtPos(board, j == 8? i+1:i, j == 8? 0:j+1) )
                    return true;
            }
        }
        
        board[i][j] = '.';
        
        return false;
    }
    
    public void solveSudoku(char[][] board) {
        solveSodukuAtPos(board, 0, 0);
        return;
    }
}

No comments:

Post a Comment