Advertisement
vladimirVenkov

Sudoku

Jun 22nd, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1.    public void solveSudoku(char[][] board) {
  2.         if(board == null || board.length == 0)
  3.             return;
  4.         solve(board);
  5.     }
  6.    
  7.     public boolean solve(char[][] board){
  8.         for(int i = 0; i < board.length; i++){
  9.             for(int j = 0; j < board[0].length; j++){
  10.                 if(board[i][j] == '.'){
  11.                     for(char c = '1'; c <= '9'; c++){//trial. Try 1 through 9
  12.                         if(isValid(board, i, j, c)){
  13.                             board[i][j] = c; //Put c for this cell
  14.                            
  15.                             if(solve(board))
  16.                                 return true; //If it's the solution return true
  17.                             else
  18.                                 board[i][j] = '.'; //Otherwise go back
  19.                         }
  20.                     }
  21.                    
  22.                     return false;
  23.                 }
  24.             }
  25.         }
  26.         return true;
  27.     }
  28.    
  29.     private boolean isValid(char[][] board, int row, int col, char c){
  30.         for(int i = 0; i < 9; i++) {
  31.             if(board[i][col] != '.' && board[i][col] == c) return false; //check row
  32.             if(board[row][i] != '.' && board[row][i] == c) return false; //check column
  33.             if(board[3 * (row / 3) + i / 3][ 3 * (col / 3) + i % 3] != '.' &&
  34. board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c) return false; //check 3*3 block
  35.         }
  36.         return true;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement