7ms Simple Java Solution


  • 0
    S
    public class Solution {
        private char[] constraint(char[][] board,int i,int j) {
            char r[]=new char[9];
            for(int k=1;k<=9;k++)  
                r[k-1]=(char)(k+48);
            
            for(int k=0;k<9;k++) { 
                if (board[i][k]!='.'){
                    r[board[i][k]-'1']='.';
                }
                if (board[k][j]!='.'){
                     r[board[k][j]-'1']='.';
                }
                int icord= (i / 3) * 3 + k%3;
                int jcord= (j / 3) * 3 + k/3;
                if (board[icord][jcord]!='.'){
                    r[board[icord][jcord]-'1']='.';
                }
            }
            return r;
        }
        public boolean next(char[][] board,int i,int j) { 
                            i++;
                            if (i==9) { i=0 ; j++; }
                            if (j==9) { return true; }
                            return solve(board,i,j);                         
        }
        private boolean solve(char[][] board,int i,int j) {
                        if (board[i][j]!='.') { 
                            return next(board,i,j);
                        }
                        char[] avail = constraint(board,i,j);
                        if (avail.length==0) return false;
                        for(int k=0;k<avail.length;k++) {
                            if (avail[k]=='.') continue;
                            board[i][j]=avail[k];
                            if (next(board,i,j))  return true;  
                        }   
                        board[i][j]='.';
                        return false;
        }
        public void solveSudoku(char[][] board) {
            solve(board,0,0);
        }
    }
    

Log in to reply
 

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