Monday, December 22, 2014

Sudoku Solver (LeetCode Hashmap)

Question: 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.

Idea: Brute force and backtracking. For each '.' block, try every number from 1-9. If it is still valid, recursively solve the rest of the board. If it is not valid, set the block back to '.' and backtrack to  the last valid point.

Time: O(n^4). Space: O(1). Actually n<=9.

Code: 
 public class Solution {  
   public void solveSudoku(char[][] board) {  
     if(board.length==0||board[0].length==0)  
     {  
       return;  
     }  
     canSolve(board);  
   }  
   public boolean canSolve(char[][] board)  
   {  
     for(int i=0;i<board.length;i++)  
     {  
       for(int j=0;j<board[0].length;j++)  
       {  
         if(board[i][j]=='.')  
         {  
           for(int k=1;k<=9;k++)  
           {  
             board[i][j]=(char)('0'+k);  
             if(isValid(board,i,j)&&canSolve(board))  
             {  
               return true;  
             }  
             board[i][j]='.';  
           }  
           return false;  
         }  
       }  
     }  
     return true;  
   }  
   public boolean isValid(char[][] board,int x,int y)  
   {  
     for(int i=0;i<board.length;i++)  
     {  
       if(i!=x&&board[i][y]==board[x][y])  
       {  
         return false;  
       }  
     }  
     for(int j=0;j<board[0].length;j++)  
     {  
       if(j!=y&&board[x][j]==board[x][y])  
       {  
         return false;  
       }  
     }  
     for(int i=3*(x/3);i<3*(x/3)+3;i++)  
     {  
       for(int j=3*(y/3);j<3*(y/3)+3;j++)  
       {  
         if((i!=x||j!=y)&&board[i][j]==board[x][y])  
         {  
           return false;  
         }  
       }  
     }  
     return true;  
   }  
 }  

No comments:

Post a Comment