Sudoku Solver
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.
Solution:
Ref: http://blog.csdn.net/fightforyourdream/article/details/16916985
Recursive + backtracking templates are used to solve this problem:
1. Determine the exit condition of DFS.
(1) If y is out of the boundary, continue to solve the problem in the next line.
(2) If X is out of the range, it indicates that the result is resolved by a single number. It should be returned.
2. DFS subject:
Traverse the nine possible values once. If it is OK (use an independent valid function to determine whether the rows, columns, and blocks match), continue DFS; otherwise, backtrack.
3. Final return value:
If true is not found for all possible traversal, false should be returned, that is, there is no solution in the current situation. At this time, DFS will automatically go back to the previous layer and look for other possible solutions.
1 public class Solution { 2 public void solveSudoku(char[][] board) { 3 dfs(board, 0, 0); 4 } 5 6 public boolean dfs(char[][] board, int x, int y) { 7 // go to next row. 8 if (y == 9) { 9 y = 0;10 x++;11 }12 13 // done14 if (x >= 9) {15 return true;16 }17 18 // Skip the solved point.19 if (board[x][y] != ‘.‘) {20 return dfs(board, x, y + 1);21 }22 23 // Go throught all the possibilities.24 for (int k = 0; k < 9; k++) {25 board[x][y] = (char)(‘1‘ + k); 26 // SHOULD RETURN HERE IF INVALID. 27 if (isValid(board, x, y) && dfs(board, x, y + 1)) {28 return true;29 }30 board[x][y] = ‘.‘;31 } 32 33 // because all the possibility is impossiable. 34 return false;35 }36 37 public boolean isValid(char[][] board, int x, int y) {38 // Judge the column.39 for (int i = 0; i < 9; i++) {40 if (i != x && board[i][y] == board[x][y]) {41 return false;42 }43 }44 45 // Judge the row.46 for (int i = 0; i < 9; i++) {47 if (i != y && board[x][i] == board[x][y]) {48 return false;49 }50 }51 52 // Judge the block.53 int i = x / 3 * 3;54 int j = y / 3 * 3;55 for (int k = 0; k < 9; k++) {56 int xIndex = i + k / 3;57 int yIndex = j + k % 3;58 if (xIndex == x && yIndex == y) {59 continue;60 }61 62 if (board[xIndex][yIndex] == board[x][y]) {63 return false;64 }65 }66 67 return true;68 }69 }
GitHub code:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/SolveSudoku.java
Leetcode: solvesudoku solution report