|
| 1 | +//this problem is easier than it looks |
| 2 | +//mix of search a 2d matrix and valid sudoku |
| 3 | + |
| 4 | +classSolution { |
| 5 | +publicvoidsolveSudoku(char[][]board) { |
| 6 | +solve(board); |
| 7 | + } |
| 8 | + |
| 9 | +publicbooleansolve(char[][]board) { |
| 10 | +//traverse the complete sudoku and look for empty value |
| 11 | +for (inti =0;i<9;i++) { |
| 12 | +for (intj=0;j<9;j++) { |
| 13 | +//look for '.' (empty block) |
| 14 | +if (board[i][j] =='.') { |
| 15 | +//try filling all values |
| 16 | +for (charc='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 | +returntrue; |
| 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 | +returnfalse; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | +returntrue; |
| 39 | + } |
| 40 | + |
| 41 | +publicbooleanisValid (char[][]board,introw,intcol,charc) { |
| 42 | +for (inti =0;i<9;i++) { |
| 43 | +//row check |
| 44 | +if (board[row][i]==c)returnfalse; |
| 45 | +//col check |
| 46 | +if (board[i][col]==c)returnfalse; |
| 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)returnfalse; |
| 52 | + } |
| 53 | +returntrue; |
| 54 | + } |
| 55 | +} |