|
| 1 | +//this problem is easier than it looks |
| 2 | +//mix of search a 2d matrix and valid sudoku |
| 3 | + |
| 4 | +class Solution { |
| 5 | + public void solveSudoku(char[][] board) { |
| 6 | + solve(board); |
| 7 | + } |
| 8 | + |
| 9 | + public boolean solve(char[][] board) { |
| 10 | + //traverse the complete sudoku and look for empty value |
| 11 | + for (int i = 0; i<9; i++) { |
| 12 | + for (int j=0; j<9; j++) { |
| 13 | + //look for '.' (empty block) |
| 14 | + if (board[i][j] == '.') { |
| 15 | + //try filling all values |
| 16 | + for (char c='1'; c<='9'; c++) { |
| 17 | + //check if we can put that value at that place |
| 18 | + //we will have a function for this which will check all the |
| 19 | + //three conditions for a valid sudoku |
| 20 | + if (isValid(board, i, j, c)) { |
| 21 | + board[i][j] = c; |
| 22 | + //check whether the new board is solvable and just return true if it is |
| 23 | + //so, we can just have only one sudoku combination. |
| 24 | + //else backtrack, i.e., make it '.' again. |
| 25 | + if (solve(board)) |
| 26 | + return true; |
| 27 | + else |
| 28 | + board[i][j] = '.'; |
| 29 | + } |
| 30 | + } |
| 31 | + //if the board[i][j] is empty and we checked all values and |
| 32 | + //nothing from '0' to '9' can be added then return false |
| 33 | + //as this is unsolvable |
| 34 | + return false; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + public boolean isValid (char[][] board, int row, int col, char c) { |
| 42 | + for (int i = 0; i<9; i++) { |
| 43 | + //row check |
| 44 | + if (board[row][i]==c) return false; |
| 45 | + //col check |
| 46 | + if (board[i][col]==c) return false; |
| 47 | + //boxes check |
| 48 | + //for this draw a sudoku and see by marking boxes and choosing a random postion |
| 49 | + //this is hard to explain but try this one |
| 50 | + //you'll get to the formula by yourself |
| 51 | + if (board[3*(row/3)+i/3][3*(col/3)+i%3]==c) return false; |
| 52 | + } |
| 53 | + return true; |
| 54 | + } |
| 55 | +} |
0 commit comments